if (!parseInt($('.pageinp').val())) $('.pageinp').val('20');
// 自定义模块
// console.log(DISPATCH_RESOURCE_URL)
var laytpl = layui.laytpl;
layui.config({
    base: DISPATCH_RESOURCE_URL + '/layui/src/js/'
}).extend({
    tableMerge: 'tableMerge'
});
var myTemplateID = ''; // 模板id
var per_page_num = $('.pageinp').val();//分页数据
var searchStartTime = '';//开始时间
var searchEndTime = '';//结束时间
var laydate = layui.laydate;
var StartTime;
var EndTime;
var longitude = '';//全局变量  经纬度
var latitude = '';//全局变量
var sortAddressId = ''; //发货地址id
var orderInNos;
sessionStorage.removeItem('sortName');
sessionStorage.removeItem('sortType');
var operateCkecked = new checkedOperation();   // 操作checked的实例对象
var operateCkecked2 = new checkedOperation();  // 操作拆单订单信息checked的实例对象
var operateCkecked3 = new checkedOperation();  // 操作拆单商品信息checked的实例对象
var stationAreaFlag = ''; // 片区内外
var isCombineFlag = localStorage.getItem('isCombineFlagOrder') ? localStorage.getItem('isCombineFlagOrder') : '0'; // 是否合单（0否1是）
// 搜索类型选择
var searchType = 'fuzzy';
var storageMethodQuery = '';

var addressHref = window.location.href;
var addressServerAddress = '';
var cleanAddress = '';
if (addressHref.indexOf('local') !== -1) {
    cleanAddress = 'http://local.address.56etms.com:83/'
    addressServerAddress = 'http://local.address.java.56etms.com:8090/';
} else if (addressHref.indexOf('dev') !== -1) {
    cleanAddress = 'http://dev.address.56etms.com/'
    addressServerAddress = 'http://local.address.java.56etms.com:8090/';
} else if (addressHref.indexOf('test') !== -1) {
    cleanAddress = 'http://test.address.56etms.com/'
    addressServerAddress = 'http://test.address.java.56etms.com/';
} else {
    //正式环境地址
    cleanAddress = 'https://address.56etms.com/'
    addressServerAddress = 'https://address.java.56etms.com/';
}
var loginName = cleanLoginName
var md5Pass = cleanPassword

var viewer1 = new Viewer(document.getElementById('dowebok1'), {
    url: 'data-original',
    zIndex: 999999
});
var viewer2 = new Viewer(document.getElementById('dowebok2'), {
    url: 'data-original',
    zIndex: 999999
});
var viewer3 = new Viewer(document.getElementById('dowebok3'), {
    url: 'data-original',
    zIndex: 999999
});
var viewer4 = new Viewer(document.getElementById('dowebok4'), {
    url: 'data-original',
    zIndex: 999999
});
var viewer5 = new Viewer(document.getElementById('dowebok5'), {
    url: 'data-original',
    zIndex: 999999
});
var viewer6 = new Viewer(document.getElementById('dowebok6'), {
    url: 'data-original',
    zIndex: 999999
});
$("#yu1,#yu4").click(function () {
    if (openFastPlanRoute) {
        viewer4.show();
    } else {
        viewer1.show();
    }
});
$("#yu2,#yu5").click(function () {
    if (openFastPlanRoute) {
        viewer5.show();
    } else {
        viewer2.show();
    }
});
$("#yu3").click(function () {
    if (openFastPlanRoute) {
        viewer6.show();
    } else {
        viewer3.show();
    }
});

if (openFastPlanRoute) {
    // $('#fast_plan_route').show();
    // $('#plan_route').hide();
    $('.template_download .simpleness_download_btn').attr('type', '精简版-手工排线.xlsx');
    $('.template_download .integrity_download_btn').attr('type', '完整版-手工排线.xlsx');
    $('#r1').val('精简版-手工排线.xlsx');
    $('#r2').val('完整版-手工排线.xlsx');
}

// 首页导入运单进入的
if (GetQueryString('upload')) {
    $('.open-window1.new_style').show();
}
// 去地址校准页面
function goAddressCorrect(pointIds) {
    if (!cleanToken) {
        var layer = layui.layer;
        loading = layer.msg('请等待！', {
            icon: 16
            , shade: 0.01
            , time: false
        });
        $.ajax({
            headers: { "Authorization-Token": User_token },
            type: "post",
            url: TRANSPORT_AJAX_URL + '/xq-route-plan-tms/auth/addressCleaninglogin',
            data: { loginName: cleanLoginName, password: md5Pass },
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            success: function success(res) {
                //token失效
                if (res.code === 100000) {
                    localStorage.clear();
                    sessionStorage.clear();
                    sessionStorage.setItem('prevUrl', window.location.href);
                    layer.msg('请求异常，请重新登录', { time: 3000 }, function () { location.href = '/Users/login'; }); return;
                }
                layer.close(loading);
                if (res.code == '100') {
                    cleanToken = res.result
                    saveErrorId(pointIds)
                } else {
                    layer.msg('服务器异常');
                }
            },
            error: function error(error) {
                layer.msg(error.msg);
            }
        });
    } else {
        saveErrorId(pointIds)
    }
}
// 获取token
function getCleanToken(res) {
    if (res.code == 100) {
        cleanToken = res.result.securityKey
    }
}
function saveErrorId(pointIds) {
    // 发请求保存所有错误的地址id
    $.ajax({
        type: "post",
        url: addressServerAddress + 'clientParamData/saveData',
        data: { token: cleanToken, data: pointIds || allPointIds },
        dataType: 'json',
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        success: function success(res) {
            if (res.businessCode == '100') {
                paramDataId = res.result
                if (paramDataId) {
                    var btoaData = window.btoa('paramDataId=' + paramDataId + '&cleanToken=' + cleanToken)
                    window.open(cleanAddress + 'view/addressCorrect/main.html?' + btoaData);
                    // window.open('http://dev.address.56etms.com:3000/view/addressCleaning/main.html?' + btoaData);
                }
            } else {
                layer.msg(res.msg);
            }
        },
        error: function error(error) {
            layer.msg(error.msg);
        }
    });
}

form.on('select(searchType)', function (data) {
    searchType = data.value;
    if ($("#fuzzy").val() != "") {
        operateCkecked.clearChecked();
        getTasksList();
    }
})
form.on('select(storageMethod)', function (data) {
    storageMethodQuery = data.value;
    operateCkecked.clearChecked();
    getTasksList();
})
if (isCombineFlag == '1') {
    $('.combineOrder').prop('checked', true);
    form.render('select', 'combineOrder-box');
}
// 监听是否合单
form.on('switch(combineOrder)', function (data) {
    if (data.elem.checked) {
        isCombineFlag = '1';
    } else {
        isCombineFlag = '0';
    }
    localStorage.setItem('isCombineFlagOrder', isCombineFlag);
    operateCkecked.clearChecked();
    whetherHaveOrder();
    getTasksList();
})
//汇总
function getTasksList(callback) {
    var fuzzy = '';//模糊搜索
    if ($("#searchStartTime").val() != '') {
        searchStartTime = "&searchStartTime=" + StartTime; //开始时间
    }
    if ($("#searchEndTime").val() != '') {
        searchEndTime = "&searchEndTime=" + EndTime;//结束时间
    }
    if ($("#fuzzy").val() != "") {
        fuzzy = "&" + searchType + "=" + $("#fuzzy").val();
    }
    //订单状态筛选
    var statusStr = '';
    if ($('.clickStatus').attr('data_status') != '') {
        statusStr = "&searchStatus=" + $('.clickStatus').attr('data_status');
    }
    var sortName = '';
    var sortType = '';
    if (sessionStorage.getItem('sortName') != null || sessionStorage.getItem('sortName') != undefined) {
        sortName = '&sortName=' + sessionStorage.getItem('sortName');
        sortType = '&sortType=' + sessionStorage.getItem('sortType');
    }
    // console.log(sortName,sortType)
    //重量筛选
    var minLoadStr = '';
    var maxLoadStr = '';
    if ($('.minLoad').val() != '') {
        minLoadStr = '&minLoad=' + $('.minLoad').val();
    }
    if ($('.maxLoad').val() != '') {
        maxLoadStr = '&maxLoad=' + $('.maxLoad').val();
    }
    var stationAreaFlagStr = '';
    if (stationAreaFlag != '') {
        stationAreaFlagStr = '&stationAreaFlag=' + stationAreaFlag
    }
    var isCombineFlagStr = '';
    if (isCombineFlag == 1) isCombineFlagStr = '&isCombineFlag=1'
    var storageMethod = '';
    if (storageMethodQuery) storageMethod = '&storageMethodQuery=' + storageMethodQuery;
    new_getTableAllData(
        TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/get',
        "pageSize=" + per_page_num + searchStartTime + searchEndTime + fuzzy + statusStr + sortName + sortType + minLoadStr + maxLoadStr + sortNameString + sortTypeString + stationAreaFlagStr + isCombineFlagStr + storageMethod,
        per_page_num,
        getVehicleListBack
    )
    // 请求获取所有的错误地址数据
    $.ajax({
        headers: { "Authorization-Token": User_token },
        type: "post",
        url: TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getPointIds',
        data: { adminId: XQ_userId, searchStatus: '7' },
        dataType: 'json',
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        success: function success(res) {
            //token失效
            if (res.code === 100000) {
                localStorage.clear();
                sessionStorage.clear();
                sessionStorage.setItem('prevUrl', window.location.href);
                layer.msg('请求异常，请重新登录', { time: 3000 }, function () { location.href = '/Users/login'; }); return;
            }
            if (res.code == 100) {
                errorAddressCount = res.result.length;
                if (res.result.length > 0) {
                    $('.address_correct_count').text(res.result.length).show()
                } else {
                    $('.address_correct_count').text(0).hide()
                }

                getAllPointIds(res)
            } else {
                layer.msg(res.msg);
            }
        },
        error: function error(error) {
            layer.msg(error.msg);
        }
    });
    summaryInfo(searchStartTime, searchEndTime, fuzzy);
}
function getAllPointIds(res) {
    allPointIds = res.result.join()
    var useCleanAddress = CookieUtil.get('useCleanAddress', useCleanAddress);
    if (allPointIds.length && useCleanAddress == 1) {
        $('#addressCorrect').removeClass('layui-btn-disabled').removeClass('disgary').addClass('gray-bg');
        $('#address_correct').removeClass('layui-btn-disabled').removeClass('disgary').addClass('gray-bg');
    } else {
        $('#addressCorrect').addClass('layui-btn-disabled').addClass('disgary').removeClass('gray-bg');
        $('#address_correct').addClass('layui-btn-disabled').addClass('disgary').removeClass('gray-bg');
    }
}
operateCkecked.allckeckedBool = true;
var customListArr = [
    { field: '3', index: '3', title: '运单编号', width: 140, sort: true, status: 1 },
    { field: '4', index: '4', title: '运单状态', width: 110, sort: true, status: 1 },
    { field: '54', index: '54', title: '错误信息', width: 110, status: 1, sort: true },
    { field: '5', index: '5', title: '任务编号', width: 110, status: 1, sort: true },
    { field: '50', index: '50', title: '片区名', width: 120, status: 1, sort: true },
    { field: '53', index: '53', title: '冷藏片区名', width: 120, status: 1 },
    { field: '6', index: '6', title: '发货地址', width: 200, status: 1, sort: true },
    { field: '49', index: '49', title: '提货地址', width: 85, status: 1 },
    { field: '7', index: '7', title: '收货城市', width: 100, status: 1, sort: true },
    { field: '45', index: '45', title: '收货区县', width: 100, status: 1, sort: true },
    { field: '48', index: '48', title: '站点编号', width: 100, status: 1 },
    { field: '8', index: '8', title: '收货站点', width: 200, status: 1, sort: true },
    { field: '9', index: '9', title: '收货详细地址', width: 300, status: 1, sort: true },
    { field: '10', index: '10', title: '下单时间', width: 150, sort: true, status: 1 },
    { field: '11', index: '11', title: '期望送达时间起', width: 150, sort: true, status: 1 },
    { field: '12', index: '12', title: '期望送达时间止', width: 150, sort: true, status: 1 },
    { field: '44', index: '44', title: '不收货时间', width: 200, status: 1 },
    { field: '13', index: '13', title: '实际送达时间', width: 135, sort: true, status: 1 },
    { field: '52', index: '52', title: '交接时间（分钟）', width: 135, status: 1 },
    { field: '14', index: '14', title: '外部单据号', width: 150, sort: true, status: 1 },
    { field: '47', index: '47', title: '储藏方式', width: 100, status: 1, sort: true },
    { field: '51', index: '51', title: '最大车型', width: 100, status: 1 },
    { field: '15', index: '15', title: '商品数量', width: 140, status: 1, sort: true },
    { field: '16', index: '16', title: '商品重量（kg）', width: 155, sort: true, status: 1 },
    { field: '17', index: '17', title: '商品体积（m³）', width: 155, sort: true, status: 1 },
    { field: '18', index: '18', title: '商品总金额', width: 110, status: 1, sort: true },
    { field: '46', index: '46', title: '商品信息', width: 85, status: 1 },
    { field: '19', index: '19', title: '备注', width: 150, status: 1 },
    { field: '20', index: '20', title: '车辆', width: 95, status: 1 },
    { field: '21', index: '21', title: '司机姓名', width: 95, status: 1 },
    { field: '22', index: '22', title: '司机电话', width: 95, status: 1 },
    { field: '23', index: '23', title: '配送方式', width: 85, status: 1 },
    { field: '24', index: '24', title: '运费单价', width: 83, status: 1 },
    { field: '25', index: '25', title: '运费', width: 83, status: 1 },
    { field: '26', index: '26', title: '保价费', width: 83, status: 1 },
    { field: '27', index: '27', title: '包装费', width: 83, status: 1 },
    { field: '28', index: '28', title: '配送费', width: 83, status: 1 },
    { field: '29', index: '28', title: '上楼费', width: 83, status: 1 },
    { field: '30', index: '30', title: '拣货费', width: 83, status: 1 },
    { field: '31', index: '31', title: '其他费用', width: 83, status: 1 },
    { field: '32', index: '32', title: '费用合计', width: 83, status: 1 },
    { field: '33', index: '33', title: '付费方式', width: 83, status: 1 },
    { field: '34', index: '34', title: '到付', width: 70, status: 1 },
    { field: '35', index: '35', title: '现付', width: 70, status: 1 },
    { field: '36', index: '36', title: '月结', width: 70, status: 1 },
    { field: '37', index: '37', title: '回单付', width: 70, status: 1 },
    { field: '38', index: '38', title: '发货人姓名', width: 115, status: 1 },
    { field: '39', index: '39', title: '发货人电话', width: 115, status: 1 },
    { field: '40', index: '40', title: '收货人姓名', width: 115, status: 1 },
    { field: '41', index: '41', title: '收货人电话', width: 115, status: 1 },
    // { field: '42', index: '42', title: '回单状态', width: 83, status: 1 },
    { field: '43', index: '43', title: '回单要求', width: 93, status: 1 }
];
// if(localStorage.getItem('customTransportPlanList') && JSON.parse(localStorage.getItem('customTransportPlanList')) instanceof Array && customListArr.length != JSON.parse(localStorage.getItem('customTransportPlanList')).length) {
//     localStorage.removeItem('customTransportPlanList');
// }
if (localStorage.getItem('customTransportPlanList') && JSON.parse(localStorage.getItem('customTransportPlanList')) instanceof Array && JSON.parse(localStorage.getItem('customTransportPlanList')).length != 51) {
    localStorage.removeItem('customTransportPlanList');
}
customListJsonFn(customListArr, 'customTransportPlanList');

var receiptMethodName = ['无需回单', '原单返回', '打收条', '签信封', '签回单盖章', '传真返回', '签回单'];
var tableHeadOrder = [[    //表头
    { field: 'td1', title: '<input type="checkbox" name="" lay-skin="primary" class="allcheck" lay-filter="allcheck">', width: 50, fixed: 'left', unresize: true },
    { field: 'td2', title: '操作', width: 120, fixed: 'left' }
]];
$.each(customListJson, function (i, item) {
    var data = {
        field: 'td' + item.field,
        title: item.title,
        width: item.width
    };
    if (item.sort) {
        data.sort = item.sort;
    }
    tableHeadOrder[0].push(data);
})
tableList('form', tableHeadOrder, null, [], 'full-218');
function getVehicleListBack(res) {
    var tableBody = [];    //表主体
    var tableFoot;
    if (res.code == 100) {
        customList();
        if (res.result.list.length > 0) {
            tableHeadOrder = [[    //表头
                { field: 'td1', title: '<input type="checkbox" name="" lay-skin="primary" class="allcheck" lay-filter="allcheck">', width: 50, fixed: 'left', unresize: true },
                { field: 'td2', title: '操作', width: 120, fixed: 'left' }
            ]];
            $.each(customListJson, function (i, item) {
                var data = {
                    field: 'td' + item.field,
                    title: item.title,
                    width: item.width
                };
                if (item.sort) {
                    data.sort = item.sort;
                }
                tableHeadOrder[0].push(data);
            })
            addCustomLists(250, tableHeadOrder, res.result.list.length);  //计算空白行的宽度
            $.each(res.result.list, function (i, item) {
                var checked = '';
                var checked1 = '';
                if (operateCkecked.allckeckedBool) {
                    checked = 'checked';
                    checked1 = 'checked';
                }
                if (operateCkecked.onlyckeckedBool) {
                    if (operateCkecked.onlyRoutes.length > 0) {
                        for (var k = 0; k < operateCkecked.onlyRoutes.length; k++) {
                            if (item.transportNo == operateCkecked.onlyRoutes[k]) {
                                checked = 'checked';
                            }
                        }
                    }
                }
                tableHeadOrder[0][0].title = '<input type="checkbox" name="" lay-skin="primary" class="allcheck" lay-filter="allcheck" ' + checked1 + '>';
                var receiptMethod = '';
                if (item.receiptMethod != null) {
                    receiptMethod = receiptMethodName[item.receiptMethod - 1];
                }
                var excludeTime = [];
                if (item.excludeTimes && item.excludeTimes.length > 0) {
                    for (var h = 0; h < item.excludeTimes.length; h++) {
                        if (item.excludeTimes[h].startTime != null) {
                            excludeTime.push(item.excludeTimes[h].startTime + '-' + item.excludeTimes[h].endTime);
                        }
                    }
                }
                var orderIdsArr = [item.orderId];
                if (isCombineFlag == 1 && item.combineOrders) {
                    orderIdsArr = [];
                    item.combineOrders.forEach(function (item, i) {
                        orderIdsArr.push(item.orderId);
                    })
                }
                var td4Name = ''
                if (item.statusName != null) {
                    if (item.status == 6) {
                        td4Name = '<span style="color:#f90">' + item.statusName + '</span>'
                    } else if (item.status == 7) {
                        td4Name = '<span style="color:red">' + item.statusName + '</span>'
                    } else {
                        td4Name = item.statusName
                    }
                }
                tableBody.push({
                    td1: item.status == 1 || item.status == 2 || item.status == 6 || item.status == 7 ? '<input type="checkbox" name="" lay-skin="primary" class="onlycheck" lay-filter="onlycheck" value="' + (isCombineFlag == 1 ? item.combineOrderNos : item.transportNo) + '" ' + checked + '>' : '',
                    td2: item.status == 1 || item.status == 6 || item.status == 7 ? "<button class='layui-btn layui-btn-small bull bull1 changeOrder' order-id='"
                        + item.orderId + "' point-id='" + item.pointId + "' originId='" + item.originId + "' unitId = '" +
                        (item.unit ? item.unit : '') + "' unitPriceId = '" + (item.unitPrice ? item.unitPrice : '') +
                        "' lay-submit lay-filter='changeOrder' order_no='" + item.transportNo + "' >修改</button>" +
                        (item.status === 7 ? '' : "<button class='layui-btn layui-btn-small bull together' orderId='"
                            + (orderIdsArr.join(",")) + "' expectedDeliveryStartTime='" + item.expectedDeliveryStartTime +
                            "' expectedDeliveryEndTime='" + item.expectedDeliveryEndTime + "' lay-submit lay-filter='together'>手工规划</button>") : "",
                    td3: item.orderDisplayNo != null ? (isCombineFlag == 1 && item.combineOrders && item.combineOrders.length > 1 ? "<button class='layui-btn layui-btn-small bull' type='button' combineOrders='" + JSON.stringify(item.combineOrders) + "' lay-submit lay-filter='lookCombineOrders'>" + item.orderDisplayNo + "</button>" : item.orderDisplayNo) : '',
                    td4: td4Name,
                    td5: item.routeDisplayNo != null ? item.routeDisplayNo : '',
                    td6: item.origin && item.origin.address ? item.origin.address : '',
                    td7: item.city != null ? item.city : '',
                    td8: item.address != null ? (item.point.stationId ? ("<span class='changeStation-btn' stationinfo='" + JSON.stringify(item.bindStation) + "' stationId='" + item.point.stationId + "'>" + item.address + "</span>") : item.address) : "",
                    td9: item.detailAddress != null ? item.detailAddress : '',
                    td10: item.bookTime ? ge_time_format(item.bookTime).substring(0, ge_time_format(item.bookTime).length - 3) : '',
                    td11: item.expectedDeliveryStartTime ? ge_time_format(item.expectedDeliveryStartTime).substring(0, ge_time_format(item.expectedDeliveryStartTime).length - 3) : '',
                    td12: item.expectedDeliveryEndTime ? ge_time_format(item.expectedDeliveryEndTime).substring(0, ge_time_format(item.expectedDeliveryEndTime).length - 3) : '',
                    td44: excludeTime.join(';'),
                    td13: item.arrivedTime ? ge_time_format(item.arrivedTime).substring(0, ge_time_format(item.arrivedTime).length - 3) : '',
                    td14: item.externalId ? item.externalId : '',
                    td15: item.quantity != null ? item.quantity : '',
                    td16: item.load != null ? item.load : '',
                    td17: item.volume != null ? item.volume : '',
                    td18: item.totalPrice ? item.totalPrice : '',
                    td46: item.goodsListVo && item.goodsListVo.length > 0 ? ("<button class='layui-btn bull' lay-submit lay-filter='lookGoods' goodsListVo='" + JSON.stringify(item.goodsListVo) + "'>查看</button>") : '',
                    td19: item.note ? item.note : '',
                    td20: item.platNo ? item.platNo : '',
                    td21: item.driverName ? item.driverName : '',
                    td22: item.driverTelphone ? item.driverTelphone : '',
                    td23: item.deliveryMethod == 1 ? "拼单" : "不拼单",
                    td24: item.unitPrice ? item.unitPrice : '',
                    td25: item.freightFees ? item.freightFees : '',
                    td26: item.valuationFees ? item.valuationFees : '',
                    td27: item.packingFees ? item.packingFees : '',
                    td28: item.deliveryFees ? item.deliveryFees : '',
                    td29: item.upstairsFees ? item.upstairsFees : '',
                    td30: item.receivingFees ? item.receivingFees : '',
                    td31: item.otherFees ? item.otherFees : '',
                    td32: item.totalFees ? item.totalFees : '',
                    td33: item.payMethodName ? item.payMethodName : '',
                    td34: item.arrivalPay ? item.arrivalPay : '',
                    td35: item.nowPay ? item.nowPay : '',
                    td36: item.monthlyPay ? item.monthlyPay : '',
                    td37: item.receiptPay ? item.receiptPay : '',
                    td38: item.shipperName ? item.shipperName : '',
                    td39: item.shipperTelphoneNo ? item.shipperTelphoneNo : '',
                    td40: item.customerName ? item.customerName : '',
                    td41: item.customerTelphoneNo ? item.customerTelphoneNo : '',
                    // td42: '',
                    td43: receiptMethod,
                    td45: item.district ? item.district : '',
                    td47: item.storageMethodName ? item.storageMethodName : '',
                    td48: item.point.stationNo ? item.point.stationNo : '',
                    td49: item.pickupStations && item.pickupStations.length > 0 ?
                        "<button class='layui-btn layui-btn-small bull bull1 lookHouse' lay-submit lay-filter='lookHouse' pickupStations='" + JSON.stringify(item.pickupStations) + "' >查看</button>" : '',
                    td50: item.areaName ? item.areaName : '',
                    td51: item.point.maxVehicleType ? item.point.maxVehicleType : '',
                    td52: item.point.handOverTime != null ? item.point.handOverTime : '',
                    td53: item.areaName2 != null ? item.areaName2 : '',
                    td54: item.errorMsg != null ? item.errorMsg : '',
                    customLists: ''
                })
            })
        }
    } else {
        layer.msg(res.msg, { time: 1500 })
    }
    tableList('form', tableHeadOrder, tableFoot, tableBody, 'full-218', drawTableSuccess);
}
function drawTableSuccess() {   //表格画完的回调函数
    //添加排序字段名
    addSortNameForTh(
        ['td3', 'td4', 'td10', 'td11', 'td12', 'td13', 'td14', 'td15', 'td16', 'td17', 'td5', 'td6', 'td7', 'td45', 'td8', 'td9', 'td47', 'td18', 'td50'],
        [
            'transportNo',
            'statusName',
            'bookTime',
            'expectedDeliveryStartTime',
            'expectedDeliveryEndTime',
            'arrivedTime',
            'externalId',
            'quantity',
            'load',
            'volume',
            'routeDisplayNo',
            'origin.address',
            'city',
            'district',
            'address',
            'detailAddress',
            'storageMethodName',
            'totalPrice',
            'areaName'
        ]);
    //表头颜色
    thBackgroundColor();
    //记录当前排序(升降)
    $('#form').next().find('.layui-table-header thead th[data-field="' + sortName + '"]').find('.layui-table-sort').attr('lay-sort', sortType);
    //隐藏未选择的列（根据status码）
    drawTableSuc(customListJson, 'form');
}
//排序
// theadSort('test',getTasksList);
//表头添加样式
function thBackgroundColor() {
    $.each($('.layui-table-header thead th'), function (i, item) {
        var a = 23;
        for (var k = 0; k < 10; k++) {
            if ($(this).attr('data-field') == 'td' + a) {
                $(this).addClass('fessColor');
            }
            a++;
        }
        var b = 33;
        for (var h = 0; h < 5; h++) {
            if ($(this).attr('data-field') == 'td' + b) {
                $(this).addClass('payColor');
            }
            b++;
        }
    })
}
// 点击分页条切换数据
// page_info(getTasksList);

//加载列表数据
// getTasksList();

//订单数
function summaryInfo(searchStartTime, searchEndTime, fuzzy) {
    //重量筛选
    var minLoadStr = '';
    var maxLoadStr = '';
    if ($('.minLoad').val() != '') {
        minLoadStr = '&minLoad=' + $('.minLoad').val();
    }
    if ($('.maxLoad').val() != '') {
        maxLoadStr = '&maxLoad=' + $('.maxLoad').val();
    }
    var stationAreaFlagStr = '';
    if (stationAreaFlag != '') {
        stationAreaFlagStr = '&stationAreaFlag=' + stationAreaFlag
    }
    var isCombineFlagStr = '';
    if (isCombineFlag == 1) isCombineFlagStr = '&isCombineFlag=1'
    var storageMethod = '';
    if (storageMethodQuery) storageMethod = '&storageMethodQuery=' + storageMethodQuery;
    $.ajax({
        headers: { "Authorization-Token": User_token },
        type: 'post',
        url: TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/planInfo',
        dataType: 'json',
        data: 'city_id=' + City_id + '&company_id=' + Company_id + '&cityId=' + City_id + '&companyId=' + Company_id + '&adminId=' + XQ_userId + searchStartTime + searchEndTime + fuzzy + minLoadStr + maxLoadStr + stationAreaFlagStr + isCombineFlagStr + storageMethod,
        success: function (res) {
            //token失效
            if (res.code === 100000) {
                localStorage.clear();
                sessionStorage.clear();
                sessionStorage.setItem('prevUrl', window.location.href);
                layer.msg('请求异常，请重新登录', { time: 3000 }, function () { location.href = '/Users/login'; }); return;
            }
            $('.order_all').html(res.result.totalOrderNum);//总订单
            $('.order_notplan').html(res.result.noPlanedNum + '/' + res.result.noPlanedColdOrderNum);//未规划
            $('.order_planed').html(res.result.planedNum);//已规划
            $('.distribution').html(res.result.assignedNum);//已分配
            $('.notribution').html(res.result.planedNum);//未分配
            $('.dispatchingNum').html(res.result.dispatchingNum);//配送中
            $('.finishedNum').html(res.result.finishedNum);//已完成
            $('.abnormalNum').html(res.result.abnormalNum);//异常
            $('.invalidOrderNum').html(res.result.invalidOrderNum);//取消
            $('.order_canplan').html(res.result.canPlannedNum);//可规划
            $('.totalOrderNum').html(res.result.noPlanedPointNum + '/' + res.result.noPlanedColdOrderPointNum);   //总站点数
        }
    })
}

//初始化弹窗
function resrevewindow1() {
    $('.open-window1').hide();
    $('.open-window1 .Fillevent').removeClass('filname').addClass('upFill');
    $('.upFill div').html('上传文件（可拖拽添加）');
    $('#seaveInfo').removeClass('green').addClass('layui-btn-disabled').addClass('gary2').prop('disabled', true);
    $('.open-window1 .Fillevent+.layui-upload-file').val('')
}

function resreveCustomImport() {
    $('.custom-import').hide();
    $('.custom-import .Fillevent').removeClass('filname').addClass('custom-upFill');
    $('.custom-upFill div').html('上传文件（可拖拽添加）');
    $('#import-custom-order').removeClass('green').addClass('layui-btn-disabled').addClass('gary2').prop('disabled', true);
    $('.custom-import .Fillevent+.layui-upload-file').val('')
}

//导入订单弹窗获取地址
function getAddressInfo() {
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/storehouse/get', { city_id: City_id, company_id: Company_id }, getAddressDothinds)
}
//展示地址
function getAddressDothinds(res) {
    if (res.code == 100) {
        $('.chockFil select').html('');
        $('.chockFil select').append('<option value="">选择发货地址</option>');
        $.each(res.result, function (i, obj) {
            $('.chockFil select').append('<option class="layui-icon layui-icon-delete" value="' + obj.subStorehouseId + '">' + obj.address + '</option>');

        });
        form.render('select')
        setTimeout(function () {
            $('.chockFil .layui-anim-upbit dd').css({
                position: "relative",
                maxWidth: '400px'
            })
            //添加删除图标
            $('.chockFil .layui-anim-upbit dd').append('<i style="position:absolute;right:0;" class="layui-icon layui-icon-delete adress_delete"></i>')
            //删除单个地址
            $('.warehouse  .layui-anim-upbit dd').css({
                position: "relative",
                maxWidth: '400px'
            })
            $(".chockFil .layui-select-tips i").hide();
            //添加地址删除图标
            $('.warehouse  .layui-anim-upbit dd').append('<i style="position:absolute;right:0;" class="layui-icon layui-icon-delete adress_delete"></i>')
            //删除单个地址
            $(".adress_delete").click(function (e) {
                e.stopPropagation()
                var subStorehouseId = $(this).parent().attr('lay-value');
                layer.confirm('<p>是否删除？</p>', {
                    title: '<span class="confirm_tips_title">温馨提示</span>',
                    btn: ['确定', '取消'],
                    shade: false
                }, function (index) {
                    layer.close(index);
                    AJAX(
                        TRANSPORT_AJAX_URL + '/xq-route-plan-tms/storehouse/deleteById',
                        { admin: XQ_userId * 1, subStorehouseId: subStorehouseId * 1 },
                        function (res) {
                            if (res.code == 100) {
                                layer.msg(res.msg, { time: 800 });
                                getAddressInfo();
                            } else {
                                layer.msg(res.msg, { time: 800 });
                            }
                        }
                    )
                }, function (index) {
                    layer.close(index);
                });
            })
        })
    }
}
//确认删除地址
$("#querySaveC").click(function () {
    AJAX(
        TRANSPORT_AJAX_URL + '/xq-route-plan-tms/storehouse/deleteById',
        { admin: XQ_userId * 1, subStorehouseId: $(".open-pop").attr("subStorehouseId") * 1 },
        function (res) {
            $(".open-pop").attr("subStorehouseId", "").hide();
            $(".mask").hide();
            if (res.code == 100) {
                layer.msg(res.msg, { time: 800 });
                getAddressInfo();
            } else {
                layer.msg(res.msg, { time: 800 });
            }
        }
    )
})
//关闭删除确认弹窗
$(".closeSave").click(function () {
    $(".open-pop").attr("subStorehouseId", "").hide();
    $(".mask").hide();
})



//查询
$("#route").click(function () {
    operateCkecked.clearChecked();
    whetherHaveOrder();
    getTasksList();
    return false;
});
$('#fuzzy').keydown(function (event) {
    if (event.keyCode == 13) {// enter搜索
        $('#route').trigger('click');
    }
});

//清空搜索框
$("#reset").click(function () {
    $('#fuzzy').val('');
    operateCkecked.clearChecked();
    whetherHaveOrder();
    getTasksList();
    return false;
});
//时间控件点击搜索
getOrdersAndRoutesStatisticsInfo({
    url: TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrdersStatisticsInfo',
    done: function (start, end) {
        StartTime = get_unix_time_stamp(start + ':00');
        searchStartTime = "&searchStartTime=" + StartTime;
        EndTime = get_unix_time_stamp(end + ':59');
        searchEndTime = "&searchEndTime=" + EndTime;
        $('.qingchu').css('background', 'url("' + DISPATCH_RESOURCE_URL + '/layui/src/images/qingchu.png") no-repeat left center');
        operateCkecked.clearChecked();
        getTasksList();
        whetherHaveOrder();
    },
    id: 'searchTime'
})
// function doHandleDate(monthNum) {
//     var myDate = new Date();
//     var tYear = myDate.getFullYear();
//     var tMonth = myDate.getMonth();
//     var m = tMonth + monthNum;
//     if(tMonth==0){
//         m = 12;
//         tYear = tYear + 1;
//     }
//     if (m <= 0) {
//         tYear = tYear - 1;
//         m = m + 12;
//     }
//     if (m.toString().length == 1) {
//         m = "0" + m;
//     }
//     return tYear +'-'+ m;
// }
//
// var markDates = []
// // 获取有运单的日期
// function getOrdersStatisticsInfo (start, end) {
//     AJAX_async(
//         TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrdersStatisticsInfo',
//         {startMonthStr: start, endMonthStr: end},
//         function (res) {
//             if (res.code == 100 && res.result && res.result.length > 0) {
//                 markDates = res.result;
//             }
//             console.log(markDates)
//         }
//     )
// }
// getOrdersStatisticsInfo (doHandleDate (-5), doHandleDate (1));
//
// var datePickerData = {
//     format: 'YYYY-MM-DD HH:mm',
//     isRange: true,
//     markDates: markDates,
//     done: function (start, end) {
//         StartTime = get_unix_time_stamp(start + ':00');
//         searchStartTime = "&searchStartTime=" + StartTime;
//         EndTime = get_unix_time_stamp(end + ':59');
//         searchEndTime = "&searchEndTime=" + EndTime;
//         $('.qingchu').css('background', 'url("' + DISPATCH_RESOURCE_URL + '/layui/src/images/qingchu.png") no-repeat left center');
//         operateCkecked.clearChecked();
//         getTasksList();
//         whetherHaveOrder ();
//     }
// }
// $("#searchTime").bind("focusin",function(){
//     $(this).datePicker(datePickerData);
// });

//日期清除
$('.qingchu').click(function () {
    $('.qingchu').css('background', 'url("' + DISPATCH_RESOURCE_URL + '/layui/src/images/kongqingchu.png") no-repeat left center');
    $("#searchStartTime").val('');
    $("#searchEndTime").val('');
    $('.minLoad,.maxLoad').val('');
    searchStartTime = '';
    searchEndTime = '';
    EndTime = '';
    StartTime = '';
    operateCkecked.clearChecked();
    getTasksList();
    whetherHaveOrder();
});

//点击筛选
$('#searchStatus a').click(function () {
    $('#searchStatus a').removeClass('clickStatus');
    $(this).addClass('clickStatus');
    operateCkecked.clearChecked();
    getTasksList();
    whetherHaveOrder();
    return false;
});

//下载模板
$("#order-download,#order_download").click(function () {
    loading = layer.msg('正在获取模板数据...', {
        time: 0,
        shade: 0.3
    });
    //跳出弹窗
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/excelconverter/getExcelColumnTemplate', {}, function (res) {
        // AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/excelconverter/getExcelColumnRecord', {}, function (res) {
        layer.close(loading);
        if (res.code == 100) {
            $('.open-window3').show();
        } else {
            layer.msg(res.msg, { time: 1800 });
        }
    });
})
// 导入界面下载固定模板
$("#templateDownload").click(function () {
    // 关闭并初始化导入界面
    resrevewindow1()

    loading = layer.msg('正在获取模板数据...', {
        time: 0,
        shade: 0.3
    });
    //跳出弹窗
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/excelconverter/getExcelColumnTemplate', {}, function (res) {
        // AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/excelconverter/getExcelColumnRecord', {}, function (res) {
        layer.close(loading);
        if (res.code == 100) {
            $('.open-window3').show();
        } else {
            layer.msg(res.msg, { time: 1800 });
        }
    });
})
// 自制导入界面下载固定模板
$('#customTemplateDownload').click(function () {
    // 关闭并初始化导入界面
    resreveCustomImport()
    $('#custom-download').trigger('click')
})
// 导入界面标识ID添加hover事件
$('.MarkId').hover(
    function () {
        $('.MarkId-tips').show();
    },
    function () {
        $('.MarkId-tips').hide();
    }
);
// 标识ID的hover事件
$('.logoId-tips-icon').hover(
    function () {
        $('.logoId-tips-hover').show();
    },
    function () {
        $('.logoId-tips-hover').hide();
    }
);

//导入订单
$('#order-input,#order_input').click(function () {
    //跳出弹窗
    $('.open-window1').show();
    getAddressInfo();
    getTransportInfoList()
});

//上传文件
// layui.upload.render({
//     elem: '.upFill'
//     , url: TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/importByFile'
//     ,accept:'file'
//     , auto:false
//     ,bindAction: '#seaveInfo' //指向一个按钮触发上传
//     ,choose: function(obj){
//         obj.preview(function(index, file, result){
//             $('.Fillevent').removeClass('upFill').addClass('filname');
//             $('.filname div').html(file.name);
//             $('#seaveInfo').removeClass('gary2').removeClass('layui-btn-disabled').addClass('green').prop('disabled',false);
//         });
//     }
//     ,before: function (input) {
//         var layer = layui.layer;
//         loading = layer.msg('上传中...', {
//             time: 0,
//             shade: 0.5
//         });
//         sortAddressId = $('.chockFil .layui-this').attr('lay-value');
//         if(sortAddressId == '' || sortAddressId == null || sortAddressId == undefined){
//             sortAddressId = '';
//         }
//         this.data={'originId':sortAddressId,adminId:XQ_userId,cityId:City_id,companyId:Company_id};
//     }
//     , field: 'excel'
//     , done: function (res) {
//         layer.close(loading);
//         var exl = res.result;
//         if (res.code == 100) {
//             layer.msg('导入成功！', {
//                 time: 800
//             });
//             //刷新数据
//             operateCkecked.allckeckedBool = true;
//             operateCkecked.onlyckeckedBool = false;
//             getTasksList();
//             operateCkecked.getAllIds(TRANSPORT_AJAX_URL+'/xq-route-plan-tms/order/getOrderNos',returnDataFn,whetherHaveOrder);
//             resrevewindow1();
//             $('.open-window1').hide();
//             if(exl != null || exl != undefined){
//                 if (!/Safari/.test(navigator.userAgent) || /Chrome/.test(navigator.userAgent)) {
//                     window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/file?filename='+encodeURI(exl.filename);
//                 }
//                 orderInNos = exl.orderNos.join(',');
//                 if(exl.cityStatus != 0) {
//                     $('.open-window4').show();
//                     $('.open-window-count-list').html('');
//                     for(var key in exl.cityNum) {
//                         var str = '<span>'+exl.cityNum[key]+'</span>个'+key+'；';
//                         $('.open-window-count-list').append(str);
//                     }
//                     province.forEach(function (item, i) {
//                         item.city.forEach(function (obj, k) {
//                             if (exl.maxCity.indexOf(obj.name) != -1) {
//                                 $('.setCity').val(item.name + '-' + obj.name);
//                             }
//                         })
//                     })
//                 }
//             }
//         } else {
//             //导入失败
//             layer.close(loading);
//             layer.confirm(res.msg, {
//                 title: '温馨提示',
//                 btn: ['我知道了'],
//                 shade: false
//             },function(index){
//                 layer.close(index);
//             });
//             $('.false-hints').html(res.msg).show();
//             setTimeout(function(){
//                 $('.false-hints').hide();
//             },3000);
//             if(exl != null || exl != undefined){
//                 window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/file?filename='+encodeURI(exl.filename);
//             }
//         }
//     }
//     , error: function (res) {
//         // 导入失败
//         layer.close(loading);
//         layer.msg('导入异常', {time: 1500});
//         $('.false-hints').show();
//         setTimeout(function(){
//             $('.false-hints').hide();
//         },3000)
//     }
// });
var excelFile;
var customExcelFile
// upFill
function initUpload(dialogName, ele, url, confirmBtnName, initWindow, done) {
    layui.upload.render({
        headers: {
            "Authorization-Token": User_token
        },
        elem: '.' + ele
        , url: TRANSPORT_AJAX_URL + url
        , accept: 'file'
        , auto: false
        , bindAction: confirmBtnName //指向一个按钮触发上传
        , choose: function (obj) {
            obj.preview(function (index, file, result) {
                $('.' + ele + '.Fillevent').removeClass(ele).addClass('filname');
                if (dialogName == 'custom-import') {
                    customExcelFile = file;
                } else {
                    excelFile = file;
                }
                $('.' + dialogName + ' .Fillevent').find('div').html(file.name)
                $(confirmBtnName).removeClass('gary2').removeClass('layui-btn-disabled').addClass('green').prop('disabled', false);
            });
        }
        , before: function (input) {
            // console.log(888)
            var layer = layui.layer;
            loading = layer.msg('上传中，请等待！', {
                icon: 16
                , shade: 0.01
                , time: false
            });
            sortAddressId = $('.chockFil .layui-this').attr('lay-value');
            sendAddress = $('.chockFil .layui-this').html()
            sendAddressOriginId = sortAddressId
            if (sortAddressId == '' || sortAddressId == null || sortAddressId == undefined) {
                sortAddressId = '';
            }
            this.data = { 'originId': sortAddressId, adminId: XQ_userId, cityId: City_id, companyId: Company_id };
        }
        , field: 'excel'
        , done: function (res) {
            if (res.code === 100000) {
                localStorage.clear();
                sessionStorage.clear();
                sessionStorage.setItem('prevUrl', window.location.href);
                layer.msg('请求异常，请重新登录', { time: 3000 }, function () { location.href = '/Users/login'; }); return;
            }
            done(res, initWindow)
        }
        , error: function (res) {
            // 导入失败
            layer.close(loading);
            layer.msg('导入异常', { time: 1500 });
            // $('.false-hints').show();
            // setTimeout(function(){
            //     $('.false-hints').hide();
            // },3000)
        }
    });
    // console.log(variable)
    // return variable;
}
initUpload('open-window1', 'upFill', '/xq-route-plan-tms/order/importByExcel', '#seaveInfo', resrevewindow1, function (res, initWindow) {
    layer.close(loading);
    var exl = res.result;
    if (res.code == 100 && !exl.fileName) {
        layer.msg('导入成功！', {
            time: 800
        });
        if (window.location.pathname === "/transport/new_transportPlan") {
            //刷新数据
            operateCkecked.allckeckedBool = true;
            operateCkecked.onlyckeckedBool = false;
            getTasksList();
            operateCkecked.getAllIds(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderNos', returnDataFn, whetherHaveOrder);
        } else {
            initAmapContainer()
        }
        initWindow();
        $('.open-window1').hide();
    } else if (res.code == 100 && exl.fileName) {
        // layer.confirm({
        //     title: '<div style="text-align:center;font-size:18px;font-weight: bold;padding-left:60px;">提示</div>'
        //     ,closeBtn: 0
        //     ,content: exl.msg
        // });
        layer.confirm(exl.msg, {
            title: '<div style="text-align:center;font-size:18px;font-weight: bold;padding-left:60px;">提示</div>',
            btn: ['确定'],
            shade: false,
            closeBtn: 0,
            // cancel: function(index){
            //     layer.close(index)  
            //     if (!/Safari/.test(navigator.userAgent) || /Chrome/.test(navigator.userAgent)) {
            //         window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/file?filename='+encodeURI(exl.fileName);
            //     }
            // }
        }, function (index) {
            layer.close(index)
            if (!/Safari/.test(navigator.userAgent) || /Chrome/.test(navigator.userAgent)) {
                window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/file?filename=' + encodeURI(exl.fileName);
            }
        });
        // layer.msg(exl.msg);
        // if (!/Safari/.test(navigator.userAgent) || /Chrome/.test(navigator.userAgent)) {
        //     window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/file?filename='+encodeURI(exl.fileName);
        // }
        if (window.location.pathname === "/transport/new_transportPlan") {
            //刷新数据
            operateCkecked.allckeckedBool = true;
            operateCkecked.onlyckeckedBool = false;
            getTasksList();
            operateCkecked.getAllIds(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderNos', returnDataFn, whetherHaveOrder);
        } else {
            initAmapContainer()
        }
        initWindow();
        $('.open-window1').hide();
    } else if (res.code == 10001) {
        if (sendAddress && sendAddressOriginId) {
            $('.sendAddress-detail').html(sendAddress)
            $('.sendAddress-detail').attr("title", sendAddress)
            $('.sendAddress').show()
        } else {
            $('.sendAddress-detail').html('')
            $('.sendAddress-detail').attr("title", '')
            $('.sendAddress').hide()
        }
        $('.open-window1').hide();
        $('.tamplate-name-box input[name="template-name"]').val('');
        addExcelTempalte(exl.colNames, exl.originId, exl.filePath, exl.autoMapping);
    } else {
        //导入失败
        layer.close(loading);
        layer.confirm(res.msg, {
            id: 'importError',
            title: '<span class="confirm_tips_title">温馨提示</span>',
            btn: ['我知道了'],
            shade: false
        }, function (index) {
            layer.close(index);
            // console.log('我知道了') 清空文件
            $('.open-window1 .Fillevent').removeClass('filname').addClass('upFill');
            $('.upFill div').html('上传文件（可拖拽添加）');
            $('#seaveInfo').removeClass('green').addClass('layui-btn-disabled').addClass('gary2').prop('disabled', true);
            $('.open-window1 .Fillevent+.layui-upload-file').val('')
        });
        // $('.false-hints').html(res.msg).show();
        // setTimeout(function(){
        //     $('.false-hints').hide();
        // },3000);
        if (exl != null || exl != undefined) {
            window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/file?filename=' + encodeURI(exl.fileName);
        }
    }
    if (location.href.indexOf('/new_transportPlan') != -1) {
        getOrdersAndRoutesStatisticsInfo({
            url: TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrdersStatisticsInfo',
            done: function (start, end) {
                StartTime = get_unix_time_stamp(start + ':00');
                searchStartTime = "&searchStartTime=" + StartTime;
                EndTime = get_unix_time_stamp(end + ':59');
                searchEndTime = "&searchEndTime=" + EndTime;
                $('.qingchu').css('background', 'url("' + DISPATCH_RESOURCE_URL + '/layui/src/images/qingchu.png") no-repeat left center');
                operateCkecked.clearChecked();
                getTasksList();
                whetherHaveOrder();
            },
            id: 'searchTime'
        });
    } else {
        getOrdersAndRoutesStatisticsInfo({
            url: TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrdersStatisticsInfo',
            id: 'delivery_time'
        })
    }
})
initUpload('custom-import', 'custom-upFill', '/xq-route-plan-tms/order/importOrderForRouteByExcel', '#import-custom-order', resreveCustomImport, function (res, initWindow) {
    layer.close(loading);
    if (res.code == 100) {
        layer.msg('导入成功！', {
            time: 800
        });
        //刷新数据
        if (!$('.list_style_container').hasClass('hidden')) {
            //刷新数据
            operateCkecked.allckeckedBool = true;
            operateCkecked.onlyckeckedBool = false;
            getTasksList();
            operateCkecked.getAllIds(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderNos', returnDataFn, whetherHaveOrder);
        } else {
            initAmapContainer()
        }
        initWindow();
        $('.custom-import').hide();
    } else {
        //导入失败
        layer.close(loading);
        layer.confirm(res.msg, {
            title: '<span class="confirm_tips_title">温馨提示</span>',
            btn: ['我知道了'],
            shade: false
        }, function (index) {
            layer.close(index);

            // $('.tamplate-name-box input[name="template-name"]').val('');
        });
        // $('.false-hints').html(res.msg).show();
        // setTimeout(function(){
        //     $('.false-hints').hide();
        // },3000);
        // if(exl != null || exl != undefined){
        //     window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/file?filename='+encodeURI(exl.fileName);
        // }
    }
})

// 去设置发货地址链接
$('.gotoSetAddress').click(function () {
    isAddressView = true
    $('.add_excel_template_box').hide(); // 打开新增模板弹窗
    $('.open-window10').show();
})

//下载模板
$('.downFill').click(function () {
    var filename = $("input[name='radio']:checked").val();
    window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/template?filename=' + encodeURI(encodeURI(filename));
})
$('.template_item .template_download>.download_btn').click(function () {
    var filename = $(this).attr('type');
    window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/template?filename=' + encodeURI(encodeURI(filename));
})
//导入订单取消按钮
$('.clossInfo').click(function () {
    resrevewindow1();
})

//选择发货地址界面取消按钮
$('#addressClossInfo').click(function () {
    isAddressView = false
    $('.open-window10').hide();
    $('.add_excel_template_box').show();
})

var sendAddress = ''
var sendAddressOriginId = 0
var isAddressView = false
// 选择发货地址界面确认按钮
$('#addressSeaveInfo').click(function () {
    sendAddress = $('.address-chockFil .layui-this').html()
    sendAddressOriginId = $('.address-chockFil .layui-this').attr('lay-value');
    if (!sendAddressOriginId) {
        layer.msg('请选择发货地址', {
            time: 1000 //2秒关闭（如果不配置，默认是3秒）
        });
        return
    }
    isAddressView = false
    if (sendAddress && sendAddressOriginId) {
        $('.sendAddress-detail').html(sendAddress)
        $('.sendAddress-detail').attr("title", sendAddress)
        $('.sendAddress').show()
    } else {
        $('.sendAddress-detail').html('')
        $('.sendAddress-detail').attr("title", '')
        $('.sendAddress').hide()
    }
    $('.open-window10').hide();
    $('.add_excel_template_box').show();
})

//下载模板取消按钮
$('#clossInfo2').click(function () {
    $('.open-window3').hide();
})

//新添地址
$('.addAddress').click(function () {
    $('.open-window1').hide();
    $('.dialog').show();
    $('#addCity').val('');
    $('.adds').val('');
})

//保存新添地址
$('.addNewStore').click(function () {
    if ($('#addCity').val() == '') {
        layer.msg('发货地址不能为空', {
            time: 1000 //2秒关闭（如果不配置，默认是3秒）
        });
        return;
    }
    if ($('.adds-bottom').val() == '') {
        layer.msg('详细地址不能为空', {
            time: 1000 //2秒关闭（如果不配置，默认是3秒）
        });
        return;
    }
    var city = $('#addCity').val().split('-');
    var address = '';
    for (var i = 0; i < city.length; i++) {
        address += city[i];
    }
    address += $('.adds').val();
    AJAX(
        '//restapi.amap.com/v3/geocode/geo?parameters',//url
        { key: '11ca106404a51e3f04745c2f710d18c0', address: address },//参数
        longiTudeDialog//回调函数
    )
});

function longiTudeDialog(res) {
    longitude = res.geocodes[0].location.split(',')[0];//分割字符串
    latitude = res.geocodes[0].location.split(',')[1];//分割字符串
    var province = res.geocodes[0].province;
    var city = res.geocodes[0].city;
    var district = res.geocodes[0].district;
    var formatted_address = res.geocodes[0].formatted_address;
    var preserve_data_dialog = {
        address: $('.adds').val(),
        longitude: longitude,
        latitude: latitude,
        district: district,
        province: province,
        city: city,
        formatted_address: formatted_address,
        city_id: City_id,
        company_id: Company_id,
    };
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/storehouse/add', preserve_data_dialog, preserveDialog)
}
//保存成功
function preserveDialog(res) {
    if (res.code == 100) {
        layer.msg('保存成功', {
            time: 800
        })
        getAddressInfo();
        if (!isAddressView) {
            $('.open-window1').show();
        }
        $('.dialog').hide();
    } else {
        layer.msg(res.msg, {
            time: 2000
        })
    }
}

//新增地址弹窗关闭
$('#ClossAdd').click(function () {
    if (!isAddressView && $('.custom-import').css('display') !== 'block') {
        $('.open-window1').show();
    }
    $('.dialog').hide();
})
$('.dislog-close').click(function () {
    if (!isAddressView && $('.custom-import').css('display') !== 'block') {
        $('.open-window1').show();
    }
    $('.dialog').hide();
})

//选择城市
$("#addCity").click(function (e) {
    SelCity(this, e);
});
//打开任务地图弹窗
$("#map_view").click(function () {
    $('#tmpl-msg').show();//地图页loading
    $('#ifr2').attr('src', '/orders/tOrderMap');//有延时
    $('.open-window2').show();
});

function OrdersCall(res) {
    if (res.code == 100) {
        allOrders = res.result.split(',');
        whetherHaveOrder();
    }
}
function getAllOrders(Data) {
    var DATA = Data;
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderNos', DATA, OrdersCall);
}

//判断是否有选中订单，更改取消运单按钮状态
function whetherHaveOrder() {
    if (operateCkecked.getIDS().split(',').length > 0 && operateCkecked.getIDS().split(',')[0] != '') {
        $('#delebill').removeClass('layui-btn-disabled').removeClass('disgary').addClass('gray-bg').prop('disabled', false);
    } else {
        $('#delebill').addClass('layui-btn-disabled').addClass('disgary').removeClass('gray-bg').prop('disabled', true);
    }
}

operateCkecked.getAllIds(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderNos', returnDataFn, whetherHaveOrder);
operateCkecked.checkedInput('allcheck', 'onlycheck', TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderNos', returnDataFn, whetherHaveOrder, whetherHaveOrder);
function returnDataFn() {   //返回筛选的参数
    var orderOutData = {};
    if ($("#searchStartTime").val() != '') {
        orderOutData.searchStartTime = StartTime;
    }
    if ($("#searchEndTime").val() != '') {
        orderOutData.searchEndTime = EndTime;
    }
    if ($("#fuzzy").val() != "") {
        orderOutData[searchType] = $("#fuzzy").val();
    }
    //订单状态筛选
    if ($('.clickStatus').attr('data_status') != '') {
        orderOutData.searchStatus = $('.clickStatus').attr('data_status');
    }
    //重量筛选
    if ($('.minLoad').val() != '') {
        orderOutData.minLoad = $('.minLoad').val();
    }
    if ($('.maxLoad').val() != '') {
        orderOutData.maxLoad = $('.maxLoad').val();
    }
    if (stationAreaFlag != '') {
        orderOutData.stationAreaFlag = stationAreaFlag;
    }
    if (storageMethodQuery != '') {
        orderOutData.storageMethodQuery = storageMethodQuery;
    }

    return orderOutData;
}

//规划点击和批量取消运单
$('#plan_route,#delebill,#map_plan_route').click(function (e) {
    var newOrders = operateCkecked.getIDS().split(',');
    if (e.target.id === 'map_plan_route') {
        newOrders = JSON.parse(JSON.stringify(newOrdersList));
    }
    // 未规划的总订单id
    var unPlannedOrders = []
    // 待补全的总订单id
    var beCompletedAllOrders = []
    // 错误的总订单id
    var errorAllOrders = []
    // 选中的订单中可规划的订单id
    var canPlanOrders = []
    // 当前的待补全订单
    var beCompletedOrders = []
    // 当前的错误订单
    var errorOrders = []

    var confirmText = '是否取消选中的运单？';
    if ($(this).attr('id') == 'plan_route' || $(this).attr('id') == 'map_plan_route') {
        var orderIdsAndStatus = []
        $.ajax({
            headers: { "Authorization-Token": User_token },
            type: 'post',
            url: DISPATCH_AJAX_URL + '/order/getOrderIdsAndStatus',
            data: { adminId: XQ_userId },
            dataType: 'json',
            success: function (res) {
                //token失效
                if (res.code === 100000) {
                    localStorage.clear();
                    sessionStorage.clear();
                    sessionStorage.setItem('prevUrl', window.location.href);
                    layer.msg('请求异常，请重新登录', { time: 3000 }, function () { location.href = '/Users/login'; }); return;
                }
                if (res.code == 100) {
                    orderIdsAndStatus = res.result
                    // 取出请求获得的所有可规划运单id
                    for (var i = 0; i < orderIdsAndStatus.length; i++) {
                        if (orderIdsAndStatus[i].status == 1) {
                            unPlannedOrders.push(orderIdsAndStatus[i].transport_no)
                        } else if (orderIdsAndStatus[i].status == 6) {
                            beCompletedAllOrders.push(orderIdsAndStatus[i].transport_no)
                        } else {
                            errorAllOrders.push(orderIdsAndStatus[i].transport_no)
                        }
                    }
                    if (orderIdsAndStatus.length != newOrders.length) {
                        // 对比所有可规划id，过滤掉选中的不可规划id
                        for (var m = 0; m < newOrders.length; m++) {
                            for (var n = 0; n < unPlannedOrders.length; n++) {
                                if (newOrders[m] == unPlannedOrders[n]) {
                                    canPlanOrders.push(newOrders[m])
                                }
                            }
                            for (var n = 0; n < errorAllOrders.length; n++) {
                                if (newOrders[m] == errorAllOrders[n]) {
                                    errorOrders.push(newOrders[m])
                                }
                            }
                            for (var n = 0; n < beCompletedAllOrders.length; n++) {
                                if (newOrders[m] == beCompletedAllOrders[n]) {
                                    beCompletedOrders.push(newOrders[m])
                                }
                            }
                        }
                    } else {      // 请求得到的所有订单数量与勾选一致，此时为全选
                        canPlanOrders = unPlannedOrders
                        beCompletedOrders = beCompletedAllOrders
                        errorOrders = errorAllOrders
                    }

                    if (canPlanOrders == null || canPlanOrders == '' || canPlanOrders == undefined) {
                        layer.msg('无可规划运单', { time: 2000 })
                    } else {
                        var path = 'new_transportPlan';
                        if (window.location.pathname === "/transport/intelligenceDispatch") {
                            path = 'intelligenceDispatch';
                        }
                        if (newOrders.length == canPlanOrders.length) {
                            sessionStorage.setItem('orderIds', canPlanOrders);
                            window.location = '/transport/routePlanning?menu_click_id=' + GetQueryString('menu_click_id') + '&scrollTop=' + $('.layui-side-scroll').scrollTop() + '&from=' + path;
                        } else {
                            var openContent = '当前可规划运单 ' + canPlanOrders.length + ' 单' + (beCompletedOrders.length ? ('；<br>待补全运单 ' + beCompletedOrders.length + ' 单') : '') + (errorOrders.length ? ('；<br>收货地址错误运单 ' + errorOrders.length + ' 单；') : '')
                            $('.layui-layer-title').css({
                                'height': '42px !important',
                                'color': 'red !important',
                                'line-height': '42px !important'
                            })
                            var btnArr = []
                            var useCleanAddress = CookieUtil.get('useCleanAddress', useCleanAddress);
                            if (errorOrders.length && useCleanAddress == 1) {
                                btnArr = ['继续规划', '去地址校准']
                            } else {
                                btnArr = ['继续规划']
                            }
                            layer.open({
                                title: '运单规划',
                                style: 'color:#333;text-align:left;font-size:11px;position:relative;',
                                content: openContent,
                                btnAlign: 'c',
                                btn: btnArr,
                                btn2: function btn1(index, layero) {
                                    layer.close(index);
                                    goAddressCorrect()
                                },
                                btn1: function btn2(index, layero) {
                                    layer.close(index);
                                    sessionStorage.setItem('orderIds', canPlanOrders);
                                    window.location = '/transport/routePlanning?menu_click_id=' + GetQueryString('menu_click_id') + '&scrollTop=' + $('.layui-side-scroll').scrollTop() + '&from=' + path;
                                },
                                btn3: function btn1(index, layero) {
                                    layer.close(index);
                                },
                            });
                        }
                    }
                } else {
                    layer.msg(res.msg)
                }
            },
            error: function () {
                layer.close(loadi);
                layer.msg('服务器异常，请稍后重试')
            }
        })

    } else {
        var orderNos = newOrders.join(',');
        layer.confirm(confirmText, {
            btn: ['确定', '取消'],
            shade: false
        }, function (index) {
            layer.close(index);
            var data = {
                cityId: City_id,
                city_id: City_id,
                companyId: Company_id,
                company_id: Company_id,
                adminId: XQ_userId,
                orderNos: orderNos
            };
            var loadi;
            $.ajax({
                headers: { "Authorization-Token": User_token },
                type: 'post',
                url: DISPATCH_AJAX_URL + '/order/cancelBatch',
                data: data,
                dataType: 'json',
                beforeSend: function (XMLHttpRequest) {
                    loadi = layer.msg('正在取消，请等待！', {
                        icon: 16
                        , shade: 0.01
                        , time: false
                    });
                },
                success: function (res) {
                    //token失效
                    if (res.code === 100000) {
                        localStorage.clear();
                        sessionStorage.clear();
                        sessionStorage.setItem('prevUrl', window.location.href);
                        layer.msg('请求异常，请重新登录', { time: 3000 }, function () { location.href = '/Users/login'; }); return;
                    }
                    layer.close(loadi);
                    deleBillBack(res)
                },
                error: function () {
                    layer.close(loadi);
                    layer.msg('服务器异常，请稍后重试')
                }
            })
        }, function (index) {
            layer.close(index);
        });
    }
});

function deleBillBack(res) {
    if (res.code == 100) {
        getOrdersAndRoutesStatisticsInfo({
            url: TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrdersStatisticsInfo',
            done: function (start, end) {
                StartTime = get_unix_time_stamp(start + ':00');
                searchStartTime = "&searchStartTime=" + StartTime;
                EndTime = get_unix_time_stamp(end + ':59');
                searchEndTime = "&searchEndTime=" + EndTime;
                $('.qingchu').css('background', 'url("' + DISPATCH_RESOURCE_URL + '/layui/src/images/qingchu.png") no-repeat left center');
                operateCkecked.clearChecked();
                getTasksList();
                whetherHaveOrder();
            },
            id: 'searchTime'
        });
        layer.msg('取消成功', { time: '500' });
        operateCkecked.clearChecked();
        getTasksList();
        whetherHaveOrder();
        $('#form').next().find('.allcheck').prop('checked', false).next().removeClass('layui-form-checked');
    } else {
        layer.msg(res.msg, { time: '500' })
    }
}

//新增订单点击
$('#addbill,#add_bill').click(function () {
    var menu_id = '44';
    if (My_XQ_Menu_Data.length > 0) {
        My_XQ_Menu_Data.forEach(function (item) {
            if (item.url == '/transport/addBill') {
                menu_id = item.id;
            }
        })
    }
    window.location = '/transport/addBill?menu_click_id=' + menu_id + '&scrollTop=' + $('.layui-side-scroll').scrollTop();
});

//跳转修改
form.on('submit(changeOrder)', function (data) {
    window.location = '/transport/modifyBill?menu_click_id=' + GetQueryString('menu_click_id') + '&orderId=' + $(data.elem).attr('order-id') + '&ponitId=' + $(data.elem).attr('point-id') + '&scrollTop=' + $('.layui-side-scroll').scrollTop() + '&orderNo=' + $(data.elem).attr('order_no');
})

//跳转手工规划
form.on('submit(together)', function (data) {
    sessionStorage.setItem('togetherOrderIds', $(data.elem).attr('orderId'))
    window.location = '/transport/routeForBill?menu_click_id=' + GetQueryString('menu_click_id')
        + '&expectedDeliveryStartTime=' + $(data.elem).attr('expectedDeliveryStartTime')
        + '&expectedDeliveryEndTime=' + $(data.elem).attr('expectedDeliveryEndTime')
        + '&scrollTop=' + $('.layui-side-scroll').scrollTop();
})

//搜索框变色
$('#fuzzy').focus(function () {
    $(this).parent().addClass('Search-inp-color')
});
$('#fuzzy').blur(function () {
    $(this).parent().removeClass('Search-inp-color')
});
// layTable(getTasksList);

//导出运单
$('#orderOut').click(function () {
    AJAX(DISPATCH_AJAX_URL + '/order/exportOrders', returnDataFn(), orderOut)
});
function orderOut(res) {
    if (res.code == 100) {
        window.location.href = DISPATCH_AJAX_URL + '/download/file?filename=' + encodeURI(res.result);
    }
}

//加载运单模板
$('#addOrderModel').click(function () {
    layer.confirm('<p>该样板数据仅供测试，实际使用前，请将其取消！</p><p>是否加载样板运单？</p>', {
        title: ['温馨提示', 'font-size:16px'],
        btn: ['确定', '取消'],
        shade: false
    }, function (index) {
        layer.close(index);
        AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/config/addStandardOrder', {}, addModelBack)
    }, function (index) {
        layer.close(index);
    });
});
function addModelBack(res) {
    if (res.code == 100) {
        operateCkecked.allckeckedBool = true;
        getTasksList();
        operateCkecked.checkedInput('allcheck', 'onlycheck', TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderNos', returnDataFn, whetherHaveOrder, whetherHaveOrder);
        operateCkecked.getAllIds(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderNos', returnDataFn, whetherHaveOrder);
    }
}

//统一城市设置取消
$('.open-window4 .info-closs,.open-window4 .clearSetCity').click(function () {
    layer.confirm('确定取消同一城市设置？', {
        btn: ['确定', '取消'],
        shade: false
    }, function (index) {
        layer.close(index);
        $('.open-window4').hide();
    }, function (index) {
        layer.close(index);
    });
});
$('.open-window4 .saveSetCity').click(function () {
    $('.open-window4').hide();
    layer.confirm('本次操作会将所有地址统一为<span class="confirmCity">' + $('.setCity').val() + '</span><p>是否确认？</p>', {
        title: ['确认信息', 'font-size:16px'],
        btn: ['确定', '放弃']
    }, function (index) {
        layer.close(index);
        loading = layer.msg('正在保存...', {
            time: 0,
            shade: 0.3
        });
        AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/updateCityBatch', {
            city: $('.confirmCity').html().split('-')[1],
            province: $('.confirmCity').html().split('-')[0],
            orderNOs: orderInNos
        }, changeCityBack);
    }, function (index) {
        layer.close(index);
        $('.open-window4').show();
    });
})
//不再提示
form.on('checkbox(noLongerTips)', function (data) {
    if (data.elem.checked) {    //选中
        localStorage.setItem('noLongerTipsSetCity', 'true');
    } else {
        localStorage.removeItem('noLongerTipsSetCity');
    }
});
//批量修改城市
$('#changeCity').click(function () {
    if (operateCkecked.getIDS().split(',').length.length == 0) {
        layer.msg('请选择运单', { time: 800 });
    } else {
        $('.open-window5').show();
    }
});
$(".changedCityName,.setCity").click(function (e) {
    SelCity(this, e, true);
    $("#_citysheng li").eq(2).hide();
});
function changeCityBack(res) {
    if (res.code == 100) {
        layer.close(loading);
        layer.msg('修改成功', { time: 800 });
        getTasksList();
        $('.open-window5').hide();
        $('.changedCityName').val('');
        operateCkecked.clearChecked();
        whetherHaveOrder();
    } else {
        layer.msg(res.msg, { time: 1500 });
    }
}

//修改城市关闭
$('.open-window5 .info-closs,#cityClose').click(function () {
    $('.open-window5').hide();
    $('.changedCityName').val('');
})

//修改城市
$('#cityUpdate').click(function () {
    if ($('.changedCityName').val() != '') {
        loading = layer.msg('正在保存...', {
            time: 0,
            shade: 0.3
        });
        AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/updateCityBatch', {
            city: $('.changedCityName').val().split('-')[1],
            province: $('.changedCityName').val().split('-')[0],
            orderNos: operateCkecked.getIDS()
        }, changeCityBack);
    } else {
        layer.msg('请填写城市', { time: 1000 });
    }
})

//重量筛选
$('.minLoad,.maxLoad').change(function () {
    if ($('.minLoad').val() != '' && $('.maxLoad').val() != '' && Number($('.minLoad').val()) >= Number($('.maxLoad').val())) {
        layer.msg('重量筛选时，后者需大于前者', { time: 1500 });
        $(this).val('');
        return;
    }
    $('.qingchu').css('background', 'url("' + DISPATCH_RESOURCE_URL + '/layui/src/images/qingchu.png") no-repeat left center');
    operateCkecked.clearChecked();
    getTasksList();
    whetherHaveOrder();
});

// 片区内外
form.on('checkbox(selectAtationAreaFlag)', function () {
    stationAreaFlag = '';
    var stationAreaFlagArr = [];
    if ($('.inArea').prop('checked')) {
        stationAreaFlagArr.push($('.inArea').val());
    }
    if ($('.outArea').prop('checked')) {
        stationAreaFlagArr.push($('.outArea').val());
    }
    stationAreaFlag = stationAreaFlagArr.join(',');
    operateCkecked.clearChecked();
    whetherHaveOrder();
    getTasksList();
});

var goodsHead = [[
    { field: 'td1', title: '商品名称', width: 200 },
    { field: 'td2', title: '商品规格', width: 150 },
    { field: 'td3', title: '商品数量', width: 140 },
    { field: 'td4', title: '商品重量(kg)', width: 140 },
    { field: 'td5', title: '商品体积(m³)', width: 140 },
]];
var goodsBody = [];
// 查看商品信息按钮点击
form.on('submit(lookGoods)', function (data) {
    $('.goodInfoBox').show();
    getGoodsInfo(JSON.parse($(data.elem).attr('goodsListVo')));
});
function getGoodsInfo(res) { // 画信息表格
    goodsHead = [[
        { field: 'td1', title: '商品名称', width: 200 },
        { field: 'td2', title: '商品规格', width: 150 },
        { field: 'td3', title: '商品数量', width: 140 },
        { field: 'td4', title: '商品重量(kg)', width: 140 },
        { field: 'td5', title: '商品体积(m³)', width: 140 },
    ]];
    goodsBody = [];
    $.each(res, function (i, item) {
        goodsBody.push({
            td1: item.name ? item.name : '',
            td2: item.specification ? item.specification : '',
            td3: isSiHai ? (item.goodsUnit && item.goodsUnit != 'null' ? item.goodsUnit : '') : (item.amount != null ? (item.amount + (item.goodsUnit && item.goodsUnit != 'null' ? item.goodsUnit : '')) : ''),
            td4: item.weight != null ? item.weight : '',
            td5: item.volume != null ? item.volume : '',
            td6: item.goodsNote ? item.goodsNote : '',
        })
    });
    tableList('goodsInfoList', goodsHead, null, goodsBody, '350');
}
$('.close-goods-info').click(function () {
    $('.goodInfoBox').hide();
});


form.on('submit(lookHouse)', function (data) {
    $('.houseInfoBox').show();
    getHouseInfo(JSON.parse($(data.elem).attr('pickupstations')));
});
function getHouseInfo(res) {
    goodsHead = [[
        { field: 'td1', title: '仓库地址', minWidth: 300 },
        { field: 'td2', title: '区县', width: 130 },
    ]];
    goodsBody = [];
    $.each(res, function (i, item) {
        goodsBody.push({
            td1: item.address ? item.address : '',
            td2: item.district ? item.district : '',
        })
    });
    tableList('houseInfoList', goodsHead, null, goodsBody, 'auto');
}
$('.close-house-info').click(function () {
    $('.houseInfoBox').hide();
});


//返回字段判空处理
function judgementNull(str) {
    var string = str;
    if (str == null) {
        string = '';
    }
    return string;
};
// 修改站点信息
var needChangeStationData = {};
$(document).on('click', '.changeStation-btn', function (e) {
    $('#add_point_info_dialog').show();
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/vehicleType/getVehicleTypeNameList', { adminId: XQ_userId }, function (response) {
        getMaxVehicleTypeListBack(response)
        getStationInfo($(e.target).attr('stationinfo'))
    })
});
$('.closeChangeStation').click(function () {
    clearChangeStationValue();
});
$('#saveChangeStation').click(function () {
    var receivingTimes = [];
    if (needChangeStationData.receivingTimes && needChangeStationData.receivingTimes.length > 0) {
        needChangeStationData.receivingTimes.forEach(function (item, i) {
            receivingTimes.push({
                receivingTimeStart: item.receivingTimeStart,
                receivingTimeEnd: item.receivingTimeEnd,
            })
        })
    }
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/station/update', {
        provinceName: needChangeStationData.provinceName,
        cityName: needChangeStationData.cityName,
        districtName: needChangeStationData.districtName,
        stationName: needChangeStationData.stationName,
        stationDetailAddress: needChangeStationData.stationDetailAddress,
        stayTime: needChangeStationData.stayTime,
        handoverTime: $('.changeStation_box .handOverTime').val(),
        queueTime: $('.changeStation_box .queueTime').val(),
        priority: needChangeStationData.priority,
        stationNo: needChangeStationData.stationNo,
        maxVehicleType: needChangeStationData.maxVehicleType,
        receivingTimeJson: receivingTimes.length > 0 ? JSON.stringify(receivingTimes) : '[]',
        id: needChangeStationData.id
    }, function (res) {
        if (res.code == 100) {
            layer.msg('站点信息修改成功', { time: 1500 });
            clearChangeStationValue();
        } else {
            layer.msg(res.msg, { time: 2000 });
        }
    })
})

function clearChangeStationValue() {
    $('.changeStation_box input').val('');
    $('.changeStation_box').hide();
    needChangeStationData = {};
}
function getNeedChangeStation(stationId) {
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/station/get', { id: stationId }, function (res) {
        if (res.code == 100) {
            needChangeStationData = res.result.list[0];
            $('.changeStation_box .handOverTime').val(res.result.list[0].handoverTime != null ? res.result.list[0].handoverTime : '');
            $('.changeStation_box .queueTime').val(res.result.list[0].queueTime != null ? res.result.list[0].queueTime : '');
        } else {
            layer.msg(res.msg, { time: 2000 });
        }
    })
}

/*------------------------------------------------------------------拆单品--------------------------------------------------------------*/
$('#splitOrderBtn,#split_order_btn').click(function () {
    if (!operateCkecked.getIDS()) {
        layer.msg('请选择运单', { time: 1000 });
        return
    }
    clearSplitSingleGoodData();
    getAreaNameByOrderNo();
    $('.splitOrderByGoods-box').show();
})

$('.closeSplitOrderByGoods').click(function () {
    $('.splitOrderByGoods-box').hide();
    clearSplitSingleGoodData();
})
var spiltOrderGoodsTableHeight = '440';
var areaNameByOrderNoTH = [[
    { field: 'td0', type: 'checkbox', fixed: 'left' },
    { field: 'td1', minWidth: 110, title: '片区名', sort: true },
    { field: 'td2', minWidth: 90, title: '商品数量', sort: true },
    { field: 'td3', minWidth: 90, title: '商品重量', sort: true },
    { field: 'td4', minWidth: 90, title: '商品体积', sort: true }
]]
var areaNameByOrderNoTB = [];

var orderByAreaNameTH = [[
    { field: 'td0', title: '<input type="checkbox" name="" lay-skin="primary" class="allcheck2" lay-filter="allcheck2">', fixed: 'left' },
    { field: 'td10', minWidth: 110, title: '片区名' },
    { field: 'td1', minWidth: 100, title: '运单编号' },
    { field: 'td2', minWidth: 100, title: '外部单据号' },
    { field: 'td11', minWidth: 200, title: '收货站点' },
    { field: 'td4', minWidth: 90, title: '商品数量' },
    { field: 'td5', minWidth: 90, title: '商品重量' },
    { field: 'td6', minWidth: 90, title: '商品体积' },
    { field: 'td3', minWidth: 200, title: '详细地址' },
    { field: 'td7', minWidth: 140, title: '下单时间' },
    { field: 'td8', minWidth: 140, title: '期望送达时间起' },
    { field: 'td9', minWidth: 140, title: '期望送达时间止' },
]]
var orderByAreaNameTB = [];

var goodByOrderNoTH = [[
    { field: 'td0', title: '<input type="checkbox" name="" lay-skin="primary" class="allcheck3" lay-filter="allcheck3">', fixed: 'left' },
    { field: 'td5', minWidth: 100, title: '外部单据号' },
    { field: 'td1', minWidth: 110, title: '商品名称' },
    { field: 'td2', minWidth: 90, title: '商品数量' },
    { field: 'td3', minWidth: 90, title: '商品重量' },
    { field: 'td4', minWidth: 90, title: '商品体积' },
]]
var goodByOrderNoTB = [];
tableList('closeSplitOrderByGoods-table-area', areaNameByOrderNoTH, null, areaNameByOrderNoTB, spiltOrderGoodsTableHeight);
tableList('closeSplitOrderByGoods-table-order', orderByAreaNameTH, null, orderByAreaNameTB, spiltOrderGoodsTableHeight, null, { text: '请选择线路' });
tableList('closeSplitOrderByGoods-table-goods', goodByOrderNoTH, null, goodByOrderNoTB, spiltOrderGoodsTableHeight, null, { text: '请选择线路和订单' });
// 拆弹商品搜索
$('#searchGoodsOrder').click(function () {
    if (operateCkecked2.getIDS() != '' && operateCkecked2.getIDS().split(',').length > 0) {
        operateCkecked3.clearChecked();
        getGoodByOrderNo();
        clearCalcGoodInfo();
    } else {
        layer.msg('请选择订单！', { time: 1500 });
    }
})
$('#goodsFuzzy').keydown(function (event) {
    if (event.keyCode == 13) {// enter搜索
        if (operateCkecked2.getIDS() != '' && operateCkecked2.getIDS().split(',').length > 0) {
            operateCkecked3.clearChecked();
            getGoodByOrderNo();
            clearCalcGoodInfo();
        } else {
            layer.msg('请选择订单！', { time: 1500 });
        }
    }
});
//清空搜索框
$("#clearGoodsOrder").click(function () {
    $('#goodsFuzzy').val('');
    if (operateCkecked2.getIDS() != '' && operateCkecked2.getIDS().split(',').length > 0) {
        operateCkecked3.clearChecked();
        getGoodByOrderNo();
        clearCalcGoodInfo();
    }
    return false;
});
// 拆弹订单搜索
$('#SplitOrderOrderSearch').click(function () {
    searchSplitOrderOrderFuzzy();
})

$('#SplitOrderOrderFuzzy').keydown(function (event) {
    if (event.keyCode == 13) {// enter搜索
        searchSplitOrderOrderFuzzy();
    }
});
//清空搜索框
$("#SplitOrderOrderClear").click(function () {
    $('#SplitOrderOrderFuzzy').val('');
    if (areaNames.length > 0) {
        searchSplitOrderOrderFuzzy();
    }
    return false;
});
function searchSplitOrderOrderFuzzy() {
    if (areaNames.length > 0) {
        chockedGoodCalcData.forEach(function (item) {
            item.orderTransportData = [];
        });
        hasOrderTransportDataNo = [];
        getOrderByAreaName(areaNames.join(','));
        goodByOrderNoTB = [];
        saveSplitSingleGoodIds = [];
        operateCkecked2.clearChecked();
        operateCkecked3.clearChecked();
        goodByOrderNoTH[0][0].title = '<input type="checkbox" name="" lay-skin="primary" class="allcheck3" lay-filter="allcheck3">';
        tableList('closeSplitOrderByGoods-table-goods', goodByOrderNoTH, null, goodByOrderNoTB, spiltOrderGoodsTableHeight, null, { text: '请选择线路和订单' });
    } else {
        layer.msg('请选择线路！', { time: 1500 });
        $('#pageSearch2').html('');
    }
}
// 拆弹线路搜索
$('#SplitOrderAreaSearch').click(function () {
    searchSplitOrderAreaFuzzy();
})

$('#SplitOrderAreaFuzzy').keydown(function (event) {
    if (event.keyCode == 13) {// enter搜索
        searchSplitOrderAreaFuzzy();
    }
});
//清空搜索框
$("#SplitOrderAreaClear").click(function () {
    $('#SplitOrderAreaFuzzy').val('');
    searchSplitOrderAreaFuzzy();
});
function searchSplitOrderAreaFuzzy() {
    areaNames = [];
    operateCkecked2.clearChecked();
    operateCkecked3.clearChecked();
    orderByAreaNameTH[0][0].title = '<input type="checkbox" name="" lay-skin="primary" class="allcheck2" lay-filter="allcheck2">';
    goodByOrderNoTH[0][0].title = '<input type="checkbox" name="" lay-skin="primary" class="allcheck3" lay-filter="allcheck3">';
    orderByAreaNameTB = [];
    goodByOrderNoTB = [];
    saveSplitSingleGoodIds = [];
    goodByOrderNos = [];
    tableList('closeSplitOrderByGoods-table-order', orderByAreaNameTH, null, orderByAreaNameTB, spiltOrderGoodsTableHeight, null, { text: '请选择线路' });
    tableList('closeSplitOrderByGoods-table-goods', goodByOrderNoTH, null, goodByOrderNoTB, spiltOrderGoodsTableHeight, null, { text: '请选择线路和订单' });
    $('#pageSearch2').html('');
    $('#pageSearch3').html('');
    getAreaNameByOrderNo();
}
var loading;
$("#saveSplitOrderByGoods").click(function () {
    if (saveSplitSingleGoodIds.length == 0) {
        layer.msg('请选择货物！', { time: 1800 });
        return
    }
    loading = layer.load(2, {
        time: 0,
        shade: 0.5,
        icon: 1
    })
    AJAX(
        TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/splitSingleGood',
        { goodIds: saveSplitSingleGoodIds.join(',') },
        function (res) {
            layer.close(loading);
            if (res.code == 100) {
                operateCkecked.clearChecked();
                getTasksList();
                layer.msg('拆单成功！', { time: 1000 });
                $('.splitOrderByGoods-box').hide();
                clearSplitSingleGoodData();
            } else {
                layer.msg(res.msg, { time: 2000 });
            }
        }
    )
})

var splitOrderSort = new XQ_Table_Sort();
// splitOrderSort.theadSort('closeSplitOrderByGoods-table-area', getAreaNameByOrderNo, true);
// 获取拆单品的运单的线路信息
function getAreaNameByOrderNo(sortNameString, sortTypeString) {
    var data = { orderNos: operateCkecked.getIDS() };
    if ($('#SplitOrderAreaFuzzy').val() != '') {
        data.fuzzy = $('#SplitOrderAreaFuzzy').val();
    }
    if (sortNameString) {
        data.sortName = sortNameString;
        data.sortType = sortTypeString;
    }
    AJAX(
        TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getAreaNameByOrderNo',
        data,
        function (res) {
            if (res.code == 100) {
                operateCkecked2.clearChecked();
                operateCkecked3.clearChecked();
                // if (res.result.length > 0) {
                // $('.closeSplitOrderByGoods-table-area-box').css('width', '26%').show();
                // $('.closeSplitOrderByGoods-table-order-box').css('width', '43%');
                // $('.closeSplitOrderByGoods-table-goods-box').css('width', '29.5%');
                areaNameByOrderNoTB = [];
                res.result.forEach(function (item, i) {
                    areaNameByOrderNoTB.push({
                        td0: item.areaName != null ? item.areaName : 'null',
                        td1: item.areaName != null ? item.areaName : '',
                        td2: item.taskAmount != null ? item.taskAmount : '',
                        td3: item.taskWeight != null ? item.taskWeight : '',
                        td4: item.taskVolume != null ? item.taskVolume : '',
                    })
                })
                // }
                // else {
                //     $('.closeSplitOrderByGoods-table-area-box').css('width', '0').hide();
                //     $('.closeSplitOrderByGoods-table-order-box').css('width', '59%');
                //     $('.closeSplitOrderByGoods-table-goods-box').css('width', '40.2%');
                //     getOrderByAreaName ('');
                // }
            }
            tableList('closeSplitOrderByGoods-table-area', areaNameByOrderNoTH, null, areaNameByOrderNoTB, spiltOrderGoodsTableHeight, function () {
                // splitOrderSort.addSortNameForTh('closeSplitOrderByGoods-table-area', [
                //     'td1', 'taskAmount', 'taskWeight', 'taskVolume'
                // ], [
                //     'areaName', 'taskAmount', 'taskWeight', 'taskVolume'
                // ])
            });
        }
    )
}

// 获取线路号下的运单信息
function getOrderByAreaName(areaNames) {
    var fuzzy = '';
    if ($('#SplitOrderOrderFuzzy').val() != '') {
        // console.log($('#SplitOrderOrderFuzzy').val())
        fuzzy = '&fuzzy=' + $('#SplitOrderOrderFuzzy').val();
    }
    getAllPagesData2(
        TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderByAreaName',
        'pageSize=20&areaNames=' + areaNames + '&orderNos=' + operateCkecked.getIDS() + fuzzy,
        20,
        function (res) {
            if (res.code == 100) {
                orderByAreaNameTB = [];
                if (res.result.list.length > 0) {
                    res.result.list.forEach(function (item, i) {
                        var checked = '';
                        var checked1 = '';
                        if (operateCkecked2.allckeckedBool) {
                            checked = 'checked';
                            checked1 = 'checked';
                        }
                        if (operateCkecked2.onlyckeckedBool) {
                            if (operateCkecked2.onlyRoutes.length > 0) {
                                for (var k = 0; k < operateCkecked2.onlyRoutes.length; k++) {
                                    if (item.transportNo == operateCkecked2.onlyRoutes[k]) {
                                        checked = 'checked';
                                    }
                                }
                            }
                        }
                        orderByAreaNameTH[0][0].title = '<input type="checkbox" name="" lay-skin="primary" class="allcheck2" lay-filter="allcheck2" ' + checked1 + '>';
                        orderByAreaNameTB.push({
                            td0: item.transportNo ? '<input type="checkbox" name="" lay-skin="primary" class="onlycheck2" lay-filter="onlycheck2" value="' + item.transportNo + '" ' + checked + '>' : '',
                            td1: item.orderDisplayNo != null ? item.orderDisplayNo : '',
                            td2: item.externalId != null ? item.externalId : '',
                            td3: item.detailAddress != null ? item.detailAddress : '',
                            td4: item.quantity != null ? item.quantity : '',
                            td5: item.load != null ? item.load : '',
                            td6: item.volume != null ? item.volume : '',
                            td7: item.bookTime != null ? get_time_format_no_s(item.bookTime) : '',
                            td8: item.expectedDeliveryStartTime ? get_time_format_no_s(item.expectedDeliveryStartTime) : '',
                            td9: item.expectedDeliveryEndTime ? get_time_format_no_s(item.expectedDeliveryEndTime) : '',
                            td10: item.areaName != null ? item.areaName : '',
                            td11: item.address != null ? item.address : '',
                            transportNo: item.transportNo
                        })
                    })
                }
            } else {
                layer.msg(res.msg, { time: 1500 });
            }
            tableList('closeSplitOrderByGoods-table-order', orderByAreaNameTH, null, orderByAreaNameTB, spiltOrderGoodsTableHeight, function () {
                showAreaOrderCalcValue();
            });
        },
        'pageSearch2'
    )
}
var storeSplitGoodsData = [];
var allGoodsDatas = [];
// 获取运单下的商品信息
function getGoodByOrderNo(callBack) {
    getAllPagesData2(
        TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getGoodByOrderNo',
        'pageSize=20&orderNos=' + goodByOrderNos.join(',') + '&goodsSearch=' + $('#goodsFuzzy').val() + '&searchStatus=1',
        20,
        function (res) {
            if (res.code == 100) {
                goodByOrderNoTB = [];
                saveSplitSingleGoodIds = [];
                if (res.result && res.result.list && res.result.list.length > 0) {
                    res.result.list.forEach(function (item, i) {
                        var checked = '';
                        var checked1 = '';
                        if (operateCkecked3.allckeckedBool) {
                            checked = 'checked';
                            checked1 = 'checked';
                        }
                        if (operateCkecked3.onlyckeckedBool) {
                            if (operateCkecked3.onlyRoutes.length > 0) {
                                for (var k = 0; k < operateCkecked3.onlyRoutes.length; k++) {
                                    if (item.goodsId == operateCkecked3.onlyRoutes[k]) {
                                        checked = 'checked';
                                    }
                                }
                            }
                        }
                        goodByOrderNoTH[0][0].title = '<input type="checkbox" name="" lay-skin="primary" class="allcheck3" lay-filter="allcheck3" ' + checked1 + '>';
                        goodByOrderNoTB.push({
                            td0: item.goodsId ? (item.isAllowSplit == '0' ? '<input type="checkbox" disabled name="" lay-skin="primary"  lay-filter="onlycheck3" value="' + item.goodsId + '">' : '<input type="checkbox" name="" lay-skin="primary" class="onlycheck3" lay-filter="onlycheck3" value="' + item.goodsId + '" ' + checked + '>') : '',
                            td1: item.name != null ? (item.isAllowSplit == '0' ? '<a class="" style="color:#cccccc">' + item.name + '</a>' : item.name) : '',
                            td2: item.amount != null ? (item.isAllowSplit == '0' ? '<a class="" style="color:#cccccc">' + item.amount + '</a>' : item.amount) : '',
                            td3: item.weight != null ? (item.isAllowSplit == '0' ? '<a class="" style="color:#cccccc">' + item.weight + '</a>' : item.weight) : '',
                            td4: item.volume != null ? (item.isAllowSplit == '0' ? '<a class="" style="color:#cccccc">' + item.volume + '</a>' : item.volume) : '',
                            td5: item.orderExternalId != null ? (item.isAllowSplit == '0' ? '<a class="" style="color:#cccccc">' + item.orderExternalId + '</a>' : item.orderExternalId) : '',
                            areaName: item.areaName ? item.areaName : '',
                            orderTransportNo: item.orderTransportNo ? item.orderTransportNo : '',
                            td10: item.goodsId
                        });
                    })
                    storeSplitGoodsData[res.result.pageNum - 1] = goodByOrderNoTB;
                }
            }
            tableList('closeSplitOrderByGoods-table-goods', goodByOrderNoTH, null, goodByOrderNoTB, spiltOrderGoodsTableHeight, function () {
                if (callBack) callBack();
            }, { text: '暂无可拆单的商品' });
        },
        'pageSearch3'
    )
    // 获取选中的订单下的全部商品信息
    AJAX(
        TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getGoodByOrderNo',
        {
            pageSize: 0,
            orderNos: goodByOrderNos.join(','),
            goodsSearch: $('#goodsFuzzy').val(),
            searchStatus: 1
        },
        function (res) {
            if (res.code == 100 && res.result && res.result.length > 0) {
                allGoodsDatas = [];
                res.result.forEach(function (item, i) {
                    allGoodsDatas.push({
                        td0: item.goodsId,
                        td1: item.name != null ? item.name : '',
                        td2: item.amount != null ? item.amount : '',
                        td3: item.weight != null ? item.weight : '',
                        td4: item.volume != null ? item.volume : '',
                        td5: item.orderExternalId != null ? item.orderExternalId : '',
                        areaName: item.areaName ? item.areaName : 'null',
                        orderTransportNo: item.orderTransportNo ? item.orderTransportNo : '',
                        isAllowSplit: item.isAllowSplit ? item.isAllowSplit : '',
                        td10: item.goodsId
                    })
                })
            }
        }
    )
}
var old_chockedGoodCalcData = [];
var areaNames = [];
table.on('checkbox(closeSplitOrderByGoods-table-area)', function (obj) {
    var tabledata = table.checkStatus('closeSplitOrderByGoods-table-area').data;
    areaNames = [];
    goodByOrderNos = [];
    goodByOrderNoTB = [];
    saveSplitSingleGoodIds = [];
    old_chockedGoodCalcData = [];
    operateCkecked2.clearChecked();
    orderByAreaNameTB = [];
    tableList('closeSplitOrderByGoods-table-order', orderByAreaNameTH, null, orderByAreaNameTB, spiltOrderGoodsTableHeight, null, { text: '请选择线路' });
    $('#pageSearch2').html('');
    operateCkecked3.clearChecked();
    tableList('closeSplitOrderByGoods-table-goods', goodByOrderNoTH, null, goodByOrderNoTB, spiltOrderGoodsTableHeight, null, { text: '请选择线路和订单' });
    $('#pageSearch3').html('');
    if (tabledata.length > 0) {
        tabledata.forEach(function (item, i) {
            areaNames.push(item.td0);
            old_chockedGoodCalcData.push({
                areaName: item.td0,
                orderTransportData: [],
                amount: 0,
                weight: 0,
                volume: 0
            })
        })
        getOrderByAreaName(areaNames.join(','));
    }
    clearCalcGoodInfo();
});

// 线路排序
table.on('sort(closeSplitOrderByGoods-table-area)', function (obj) {
    var sortAreaTB = JSON.parse(JSON.stringify(areaNameByOrderNoTB));
    areaNameByOrderNoTB = [];
    $.each($('.closeSplitOrderByGoods-table-area-box .layui-table-main tr td[data-field="td1"]'), function () {
        var that = $(this);
        sortAreaTB.forEach(function (val) {
            if (that.find('.layui-table-cell').html() == val.td1) {
                areaNameByOrderNoTB.push(val);
            }
        })
    })
    var tabledata = [];
    chockedGoodCalcData = JSON.parse(JSON.stringify(old_chockedGoodCalcData)); // 深拷贝线路信息数据
    if (operateCkecked3.getIDS() != '' && operateCkecked3.getIDS().split(',').length > 0) {
        operateCkecked3.getIDS().split(',').forEach(function (item, i) {
            allGoodsDatas.forEach(function (val, k) {
                if (val.td10 == item) {
                    tabledata.push(val);
                }
            })
        })
        tabledata.forEach(function (item, i) {
            chockedGoodCalcData.forEach(function (val, l) {
                if (val.areaName == item.areaName) {
                    val.amount = XQ_Value_Calc_Fns.Add(Number(item.td2), val.amount);
                    val.weight = XQ_Value_Calc_Fns.Add(Number(item.td3), val.weight);
                    val.volume = XQ_Value_Calc_Fns.Add(Number(item.td4), val.volume);
                    if (val.orderTransportData.length == 0) {
                        val.orderTransportData.push({
                            orderTransportNo: Number(item.orderTransportNo),
                            orderAmount: Number(item.td2),
                            orderWeight: Number(item.td3),
                            orderVolume: Number(item.td4),
                        })
                        hasOrderTransportDataNo.push(Number(item.orderTransportNo));
                    } else {
                        var isHas = false;
                        val.orderTransportData.forEach(function (res, k) {
                            if (res.orderTransportNo == item.orderTransportNo) {
                                res.orderAmount = XQ_Value_Calc_Fns.Add(Number(item.td2), res.orderAmount);
                                res.orderWeight = XQ_Value_Calc_Fns.Add(Number(item.td3), res.orderWeight);
                                res.orderVolume = XQ_Value_Calc_Fns.Add(Number(item.td4), res.orderVolume);
                                isHas = true;
                            }
                        })
                        if (!isHas) {
                            val.orderTransportData.push({
                                orderTransportNo: Number(item.orderTransportNo),
                                orderAmount: Number(item.td2),
                                orderWeight: Number(item.td3),
                                orderVolume: Number(item.td4),
                            })
                            hasOrderTransportDataNo.push(Number(item.orderTransportNo));
                        }
                    }
                }
            })
            // 只有可以拆单的订单才加入拆单品列表
            if (item.isAllowSplit == '' || item.isAllowSplit == null || item.isAllowSplit == undefined || item.isAllowSplit == 1) {
                saveSplitSingleGoodIds.push(item.td10);
            }
        });
        chockedGoodCalcData.forEach(function (item, i) {
            areaNameByOrderNoTB.forEach(function (val, k) {
                var amountBox = $('.closeSplitOrderByGoods-table-area-box .layui-table-main tbody tr').eq(k).find('td[data-field="td2"] .layui-table-cell')
                var weightBox = $('.closeSplitOrderByGoods-table-area-box .layui-table-main tbody tr').eq(k).find('td[data-field="td3"] .layui-table-cell')
                var volumeBox = $('.closeSplitOrderByGoods-table-area-box .layui-table-main tbody tr').eq(k).find('td[data-field="td4"] .layui-table-cell')
                if (val.td0 == item.areaName && item.orderTransportData.length > 0) {
                    amountBox.html(XQ_Value_Calc_Fns.Sub(Number(val.td2), item.amount)).addClass('calcedColor');
                    weightBox.html(XQ_Value_Calc_Fns.Sub(Number(val.td3), item.weight)).addClass('calcedColor');
                    volumeBox.html(XQ_Value_Calc_Fns.Sub(Number(val.td4), item.volume)).addClass('calcedColor');
                }
                if (val.td0 == item.areaName && item.orderTransportData.length == 0) {
                    amountBox.html(val.td2).removeClass('calcedColor');
                    weightBox.html(val.td3).removeClass('calcedColor');
                    volumeBox.html(val.td4).removeClass('calcedColor');
                }
            })
        });
    }
});

var goodByOrderNos = [];
var saveSplitSingleGoodIds = [];
var chockedGoodCalcData = []; // 选择商品后计算订单和线路减去的数量、重量、体积
var hasOrderTransportDataNo = [];

// 拆单品初始化
function clearSplitSingleGoodData() {
    $('#goodsFuzzy').val('');
    $('#SplitOrderAreaFuzzy').val('');
    $('#SplitOrderOrderFuzzy').val('');
    areaNames = [];
    areaNameByOrderNoTB = [];
    orderByAreaNameTB = [];
    goodByOrderNoTB = [];
    saveSplitSingleGoodIds = [];
    goodByOrderNos = [];
    goodByOrderNoTH[0][0].title = '<input type="checkbox" name="" lay-skin="primary" class="allcheck3" lay-filter="allcheck3">';
    orderByAreaNameTH[0][0].title = '<input type="checkbox" name="" lay-skin="primary" class="allcheck2" lay-filter="allcheck2">';
    tableList('closeSplitOrderByGoods-table-area', areaNameByOrderNoTH, null, areaNameByOrderNoTB, spiltOrderGoodsTableHeight);
    tableList('closeSplitOrderByGoods-table-order', orderByAreaNameTH, null, orderByAreaNameTB, spiltOrderGoodsTableHeight, null, { text: '请选择线路' });
    tableList('closeSplitOrderByGoods-table-goods', goodByOrderNoTH, null, goodByOrderNoTB, spiltOrderGoodsTableHeight, null, { text: '请选择线路和订单' });
    $('#pageSearch2').html('');
    $('#pageSearch3').html('');
    // splitOrderSort.initialize ();
    operateCkecked2.clearChecked();
    operateCkecked3.clearChecked();
}

function clearCalcGoodInfo() {
    areaNameByOrderNoTB.forEach(function (val, k) {
        var amountBox = $('.closeSplitOrderByGoods-table-area-box .layui-table-main tbody tr').eq(k).find('td[data-field="td2"] .layui-table-cell')
        amountBox.html(val.td2).removeClass('calcedColor');
        var weightBox = $('.closeSplitOrderByGoods-table-area-box .layui-table-main tbody tr').eq(k).find('td[data-field="td3"] .layui-table-cell')
        weightBox.html(val.td3).removeClass('calcedColor');
        var volumeBox = $('.closeSplitOrderByGoods-table-area-box .layui-table-main tbody tr').eq(k).find('td[data-field="td4"] .layui-table-cell')
        volumeBox.html(val.td4).removeClass('calcedColor');
    })
    orderByAreaNameTB.forEach(function (val, k) {
        var amountBox = $('.closeSplitOrderByGoods-table-order-box .layui-table-main tbody tr').eq(k).find('td[data-field="td4"] .layui-table-cell')
        amountBox.html(val.td4).removeClass('calcedColor');
        var weightBox = $('.closeSplitOrderByGoods-table-order-box .layui-table-main tbody tr').eq(k).find('td[data-field="td5"] .layui-table-cell')
        weightBox.html(val.td5).removeClass('calcedColor');
        var volumeBox = $('.closeSplitOrderByGoods-table-order-box .layui-table-main tbody tr').eq(k).find('td[data-field="td6"] .layui-table-cell')
        volumeBox.html(val.td6).removeClass('calcedColor');
    })
    chockedGoodCalcData = [];
}

// 商品信息多选事件
operateCkecked3.checkedInput('allcheck3', 'onlycheck3', TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getGoodIds', checkedGoodsDataFn, checkedGoodsCallBack, checkedGoodsCallBack);
// 商品全选获取全部id接口的请求参数
function checkedGoodsDataFn() {
    return {
        goodsSearch: $('#goodsFuzzy').val(),
        searchStatus: 1,
        orderNos: operateCkecked2.getIDS()
    }
}
// 商品信息全选和多选回调执行
function checkedGoodsCallBack() {
    var tabledata = [];
    saveSplitSingleGoodIds = [];
    hasOrderTransportDataNo = [];
    chockedGoodCalcData = JSON.parse(JSON.stringify(old_chockedGoodCalcData)); // 深拷贝线路信息数据
    if (operateCkecked3.getIDS() != '' && operateCkecked3.getIDS().split(',').length > 0) {
        operateCkecked3.getIDS().split(',').forEach(function (item, i) {
            allGoodsDatas.forEach(function (val, k) { // 遍历全部商品信息数据
                if (val.td10 == item) {
                    tabledata.push(val); // 组装已选中的商品数据
                }
            })
        })
        tabledata.forEach(function (item, i) { // 遍历选中了的商品信息
            chockedGoodCalcData.forEach(function (val, l) { // 遍历选中的线路数据
                if (val.areaName == item.areaName) { // 该商品信息属于该线路时，封装包含商品信息和订单信息的线路数据
                    val.amount = XQ_Value_Calc_Fns.Add(Number(item.td2), val.amount);
                    val.weight = XQ_Value_Calc_Fns.Add(Number(item.td3), val.weight);
                    val.volume = XQ_Value_Calc_Fns.Add(Number(item.td4), val.volume);
                    if (val.orderTransportData.length == 0) {
                        val.orderTransportData.push({
                            orderTransportNo: Number(item.orderTransportNo),
                            orderAmount: Number(item.td2),
                            orderWeight: Number(item.td3),
                            orderVolume: Number(item.td4),
                        })
                        hasOrderTransportDataNo.push(Number(item.orderTransportNo));
                    } else {
                        var isHas = false;
                        val.orderTransportData.forEach(function (res, k) {
                            if (res.orderTransportNo == item.orderTransportNo) {
                                res.orderAmount = XQ_Value_Calc_Fns.Add(Number(item.td2), res.orderAmount);
                                res.orderWeight = XQ_Value_Calc_Fns.Add(Number(item.td3), res.orderWeight);
                                res.orderVolume = XQ_Value_Calc_Fns.Add(Number(item.td4), res.orderVolume);
                                isHas = true;
                            }
                        })
                        if (!isHas) {
                            val.orderTransportData.push({
                                orderTransportNo: Number(item.orderTransportNo),
                                orderAmount: Number(item.td2),
                                orderWeight: Number(item.td3),
                                orderVolume: Number(item.td4),
                            })
                            hasOrderTransportDataNo.push(Number(item.orderTransportNo));
                        }
                    }
                }
            })
            // 只有可以拆单的订单才加入拆单品列表
            if (item.isAllowSplit == '' || item.isAllowSplit == null || item.isAllowSplit == undefined || item.isAllowSplit == 1) {
                saveSplitSingleGoodIds.push(item.td10);
            }
        });
        showAreaOrderCalcValue(); // 显示计算后的结果
    }
    if (saveSplitSingleGoodIds.length == 0) {
        clearCalcGoodInfo(); // 清空计算后的结果
    }
}
// 计算线路信息和订单信息的商品结果
function showAreaOrderCalcValue() {
    chockedGoodCalcData.forEach(function (item, i) { // 遍历封装好了的线路信息数据 (包括线路名、线路下的订单、订单下的商品信息数据)
        // 线路信息减去已选商品数量、重量、体积
        areaNameByOrderNoTB.forEach(function (val, k) {
            var amountBox = $('.closeSplitOrderByGoods-table-area-box .layui-table-main tbody tr').eq(k).find('td[data-field="td2"] .layui-table-cell')
            var weightBox = $('.closeSplitOrderByGoods-table-area-box .layui-table-main tbody tr').eq(k).find('td[data-field="td3"] .layui-table-cell')
            var volumeBox = $('.closeSplitOrderByGoods-table-area-box .layui-table-main tbody tr').eq(k).find('td[data-field="td4"] .layui-table-cell')
            if (val.td0 == item.areaName && item.orderTransportData.length > 0) {
                amountBox.html(XQ_Value_Calc_Fns.Sub(Number(val.td2), item.amount)).addClass('calcedColor');
                weightBox.html(XQ_Value_Calc_Fns.Sub(Number(val.td3), item.weight)).addClass('calcedColor');
                volumeBox.html(XQ_Value_Calc_Fns.Sub(Number(val.td4), item.volume)).addClass('calcedColor');
            }
            if (val.td0 == item.areaName && item.orderTransportData.length == 0) {
                amountBox.html(val.td2).removeClass('calcedColor');
                weightBox.html(val.td3).removeClass('calcedColor');
                volumeBox.html(val.td4).removeClass('calcedColor');
            }
        })
        // 订单信息减去已选商品数量、重量、体积
        orderByAreaNameTB.forEach(function (val, k) {
            var amountBox = $('.closeSplitOrderByGoods-table-order-box .layui-table-main tbody tr').eq(k).find('td[data-field="td4"] .layui-table-cell')
            var weightBox = $('.closeSplitOrderByGoods-table-order-box .layui-table-main tbody tr').eq(k).find('td[data-field="td5"] .layui-table-cell')
            var volumeBox = $('.closeSplitOrderByGoods-table-order-box .layui-table-main tbody tr').eq(k).find('td[data-field="td6"] .layui-table-cell')
            item.orderTransportData.forEach(function (res, l) {
                if (val.transportNo == res.orderTransportNo) {
                    amountBox.html(XQ_Value_Calc_Fns.Sub(Number(val.td4), res.orderAmount)).addClass('calcedColor');
                    weightBox.html(XQ_Value_Calc_Fns.Sub(Number(val.td5), res.orderWeight)).addClass('calcedColor');
                    volumeBox.html(XQ_Value_Calc_Fns.Sub(Number(val.td6), res.orderVolume)).addClass('calcedColor');
                }
            })
            if (hasOrderTransportDataNo.indexOf(Number(val.transportNo)) < 0) {
                amountBox.html(val.td4).removeClass('calcedColor');
                weightBox.html(val.td5).removeClass('calcedColor');
                volumeBox.html(val.td6).removeClass('calcedColor');
            }
        });
    });
}
// 订单信息多选事件
operateCkecked2.checkedInput('allcheck2', 'onlycheck2', TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderNosByAreaName', checkedGoodOrdersDataFn, checkedGoodOrdersCallBack, checkedGoodOrdersCallBack);
// 获取订单信息全部id接口的请求参数
function checkedGoodOrdersDataFn() {
    return {
        fuzzy: $('#SplitOrderOrderFuzzy').val(),
        areaNames: areaNames.join(','),
        orderNos: operateCkecked.getIDS()
    }
}
// 订单信息多选和单选回调执行
function checkedGoodOrdersCallBack() {
    var tabledata = operateCkecked2.getIDS().split(',');
    goodByOrderNos = [];
    operateCkecked3.clearChecked();
    saveSplitSingleGoodIds = [];
    clearCalcGoodInfo();
    if (operateCkecked2.getIDS() != '' && tabledata.length > 0) { // 有选中的订单信息
        tabledata.forEach(function (item, i) {
            goodByOrderNos.push(item);
        })
        getGoodByOrderNo();
    } else {
        goodByOrderNoTB = [];
        tableList('closeSplitOrderByGoods-table-goods', goodByOrderNoTH, null, goodByOrderNoTB, spiltOrderGoodsTableHeight, null, { text: '请选择线路和订单' });
        $('#pageSearch3').html('');
    }
}

// 更多操作点击
$('#moreOrderOperationBtn').click(function (e) {
    e.stopPropagation() || window.event.cancelBubble
    isShowMoreOrderOperationBtns();
})
// 更多操作回调
function isShowMoreOrderOperationBtns() {
    if ($('.moreOrderOperationBtns').hasClass('moreOperationActive')) {
        $('.orderOperationBtns').fadeOut(300);
        $('.moreOrderOperationBtns').removeClass('moreOperationActive');
        $('.moreOrderOperationBtns').find('.layui-icon').removeClass('layui-icon-up').addClass('layui-icon-down');
    } else {
        $('.orderOperationBtns').fadeIn(300);
        $('.moreOrderOperationBtns').addClass('moreOperationActive')
        $('.moreOrderOperationBtns').find('.layui-icon').removeClass('layui-icon-down').addClass('layui-icon-up');
    }
}
// 页面点击关闭更多操作框
$(document).click(function () {
    if ($('.moreOrderOperationBtns').hasClass('moreOperationActive')) {
        isShowMoreOrderOperationBtns();
    }
    $('.header_btns .order_operation_btns').hide()
})

// 合单详情显示
var combineOrderChildTh = [[
    { field: 'td1', title: '运单编号', width: 135 },
    { field: 'td5', title: '外部订单号', width: 135 },
    { field: 'td7', title: '收货详细地址', width: 250 },
    { field: 'td2', title: '商品数量', width: 90 },
    { field: 'td3', title: '商品重量（kg）', width: 130 },
    { field: 'td4', title: '商品体积（m³）', width: 130 },
    { field: 'td6', title: '商品详情', width: 90 },
]]
var combineOrderChildTB = [];
form.on('submit(lookCombineOrders)', function (data) {
    var combineOrders = JSON.parse($(data.elem).attr('combineOrders'));
    combineOrderChildTB = []
    combineOrders.forEach(function (item) {
        combineOrderChildTB.push({
            td1: item.orderDisplayNo ? item.orderDisplayNo : '',
            td2: item.quantity ? item.quantity : '0',
            td3: item.load ? item.load : '0',
            td4: item.volume ? item.volume : '0',
            td5: item.externalId ? item.externalId : '',
            td6: "<button class='layui-btn bull' type='button' lay-submit lay-filter='lookGoodsCombineOrder' orderNo='" + item.transportNo + "'>查看</button>",
            td7: item.detailAddress ? item.detailAddress : '',
        })
    })
    tableList('combineOrderChild_table', combineOrderChildTh, null, combineOrderChildTB, 300);
    $('.combineOrderChild_box').show();
})

$('.closeCombineOrderChild').click(function () {
    $('.combineOrderChild_box').hide();
})

form.on('submit(lookGoodsCombineOrder)', function (data) {
    AJAX(
        TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getCombineGood',
        { orderNo: $(data.elem).attr('orderNo') },
        function (res) {
            if (res.code == 100 && res.result) {
                getGoodsInfo(res.result);
            }
            $('.combineOrderChild_box').hide();
            $('.goodInfoBox').show();
            $('.goodInfoBox .info-closs, .goodInfoBox .XQ_dialog_btns button').removeClass('close-goods-info').addClass('close-combineOrder-goods');
        }
    )

})
$('.goodInfoBox').on('click', '.close-combineOrder-goods', function () {
    $('.combineOrderChild_box').show();
    $('.goodInfoBox').hide();
    $('.goodInfoBox .info-closs, .goodInfoBox .XQ_dialog_btns button').addClass('close-goods-info').removeClass('close-combineOrder-goods');
})


// 下载自制模板
$('#custom-download,#custom_download').click(function () {
    window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/template?filename=' + encodeURI(encodeURI('自有线路导入模板.xlsx'));
});

//导入自制运单
// /xq-route-plan-tms/order/importOrderForRouteByExcel
$('#custom-import,#custom_import').click(function () {
    //跳出弹窗
    $('.custom-import').show();
    getAddressInfo();
})
$('#close-custom-order').click(function () {
    resreveCustomImport()
})

$('#toggle_mode_btn').click(function () {
    var menu_id = '9955';
    if (My_XQ_Menu_Data.length > 0) {
        My_XQ_Menu_Data.forEach(function (item) {
            if (item.url == '/transport/intelligenceDispatch') {
                menu_id = item.id;
            }
        })
    }
    window.location = '/transport/intelligenceDispatch?menu_click_id=' + menu_id + '&scrollTop=0';

    // $('.rightCont').toggle();
    // initAmapContainer();
})

function initTransportPlan() {
    tableList('form', tableHeadOrder, null, [], 'full-250');
    //排序
    theadSort('test', getTasksList);
    // 点击分页条切换数据
    page_info(getTasksList);
    operateCkecked.allckeckedBool = true;
    operateCkecked.onlyckeckedBool = false;
    //加载列表数据
    getTasksList();
    operateCkecked.getAllIds(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrderNos', returnDataFn, whetherHaveOrder);
    layTable(getTasksList);
}

if (window.location.pathname !== "/transport/intelligenceDispatch") {
    initTransportPlan()
}


var IMPORT_IND_TEM_URL = '/xq-route-plan-tms/initOrderData/importIndustryTemplateData';

function importIndTem(industry) {
    var name = '';
    industry === '1' ? (name = '医药') : (name = '快消');
    var confirmText = '<div class="confirm_content">该样板数据仅供测试，实际使用前，请将其取消！</div>' +
        '<div class="confirm_tips">是否导入样板运单？</div>';
    layer.confirm(confirmText, {
        title: '<span class="confirm_tips_title">温馨提示</span>',
        // closeBtn : true,
        btn: ['导入', '取消'],
        // btnAlign: 'c',
        area: ['auto', 'auto'],
        shade: .5
    }, function (index) {
        layer.close(index);
        loading = layer.msg('正在导入，请等待！', {
            icon: 16
            , shade: 0.01
            , time: false
        });
        // loading = layer.load(2,{
        //     time: 0,
        //     shade:0.5,
        //     icon:1
        // })
        AJAX(TRANSPORT_AJAX_URL + IMPORT_IND_TEM_URL, { city_id: City_id, company_id: Company_id, industry: industry }, function (res) {
            if (res.code === 100) {
                layer.close(loading)
                $('.open-window1').hide();
                if (window.location.pathname === "/transport/new_transportPlan") {
                    initTransportPlan()
                } else {
                    initAmapContainer()
                }
                if (location.href.indexOf('/new_transportPlan') != -1) {
                    getOrdersAndRoutesStatisticsInfo({
                        url: TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrdersStatisticsInfo',
                        done: function (start, end) {
                            StartTime = get_unix_time_stamp(start + ':00');
                            searchStartTime = "&searchStartTime=" + StartTime;
                            EndTime = get_unix_time_stamp(end + ':59');
                            searchEndTime = "&searchEndTime=" + EndTime;
                            $('.qingchu').css('background', 'url("' + DISPATCH_RESOURCE_URL + '/layui/src/images/qingchu.png") no-repeat left center');
                            operateCkecked.clearChecked();
                            getTasksList();
                            whetherHaveOrder();
                        },
                        id: 'searchTime'
                    });
                } else {
                    getOrdersAndRoutesStatisticsInfo({
                        url: TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getOrdersStatisticsInfo',
                        id: 'delivery_time'
                    })
                }
            } else {
                layer.msg(res.msg, {
                    time: 3000
                })
            }
            layer.close(loading)
        })
    }, function (index) {
        layer.close(index);
    });
}
$('.template_download>.import_btn').click(function () {
    importIndTem($(this).attr('type'))
})

var errorAddressCount = 0;

$('#addressCorrect').mouseenter(function (e) {
    e && e.stopPropagation ? e.stopPropagation() : window.event.cancelBubble = true;
    var tipsContent = ''
    var useCleanAddress = CookieUtil.get('useCleanAddress', useCleanAddress);
    if (useCleanAddress !== '1') {
        tipsContent = '地址校准功能未开启，请到系统配置页面开启';
    } else {
        if ($(this).hasClass('layui-btn-disabled')) {
            tipsContent = '运单地址正确，无需校准';
        } else {
            tipsContent = '存在' + errorAddressCount + '条地址错误运单，请点击按钮进行地址清洗'
        }
    }

    tips = layer.tips('<div>' + tipsContent + '</div>', $(this), {
        tips: [1, 'rgba(0,0,0,0.8)'],
        area: ['auto', 'auto'],
        time: 0
    });
})
$('#addressCorrect').mouseleave(function (e) {
    layer.close(tips);
})



//防止重复调用

if (window.location.href.indexOf('transportPlan') !== -1) {

    var GET_STATION_INFO_URL = '/xq-route-plan-tms/station/getById';
    var UPDATE_STATION_INFO_URL = '/xq-route-plan-tms/station/update';
    $('#add_point_info_dialog .dialog_close').click(function () {
        $(this).parents('.__dialog').fadeOut(500)
        clearStationInput()
    })
    //清空input及select值
    function clearStationInput() {
        $('#add_point_info_dialog input').not('#fuzzy,.pageinp,.layui-laypage-skip,.pingjunTime,.jietiTime,.noTime,.typeWeight,.typeNumber,.typeVolume,input[name=isKeyAccount]').val('');
        $('#add_point_info_dialog select').next().find('dd').removeClass('layui-this');
        $('#add_point_info_dialog .timeBox>div').remove();
        $('#add_point_info_dialog input[name=isKeyAccount]').first().prop('checked', 'checked')
        var str = '<div class="unreceived_window"><div class="c-datepicker-date-editor J-datepickerTime-range datepicker-searchTime">' +
            '<i class="c-datepicker-range__icon kxiconfont icon-clock"></i>' +
            '<input autocomplete="off" placeholder="开始时间" class="c-datepicker-data-input c-timepicker-time-input startTime" id="startTime' + timeIndex + '">' +
            '<span class="c-datepicker-range-separator">-</span>' +
            '<input autocomplete="off" placeholder="结束时间" class="c-datepicker-data-input c-timepicker-time-input endTime" id="endTime' + timeIndex + '">' +
            '</div>' +
            '<a class="layui-inline imgIco deleIco" href="javascript:;"></a>' +
            '<a class="layui-inline imgIco addIco" href="javascript:;"></a></div>';
        $('#add_point_info_dialog .timeBox').append(str);
        $('#add_point_info_dialog .listTime').height(36);
        var st = '<div class="c-datepicker-date-editor J-datepickerTime-range datepicker-searchTime-open">' +
            '                                        <i class="c-datepicker-range__icon kxiconfont icon-clock"></i>' +
            '                                        <input autocomplete="off" placeholder="开始时间" class="c-datepicker-data-input c-timepicker-time-input startTime" id="goodsStartTime">' +
            '                                        <span class="c-datepicker-range-separator">-</span>' +
            '                                        <input autocomplete="off" placeholder="结束时间" class="c-datepicker-data-input c-timepicker-time-input endTime" id="goodsEndTime">' +
            '                                    </div>'
        $('#add_point_info_dialog .timeBox1 > div').html(st);
        $('#add_point_info_dialog input:radio').each(function (index, el) {
            el.checked = false;
        });
        $("#add_point_info_dialog .noTime").prop("checked", true);
        $("#add_point_info_dialog .typeWeight").prop("checked", true);
        $('.handoverTimeType').val('0')
        $('.handoverTimeMethod').val('1')
        $("#add_point_info_dialog .ladderTimeBox").hide();
        $("#add_point_info_dialog .handOverTimeBox").hide();
        $("#add_point_info_dialog .ladderUite").text("kg")
        var content =
            '   <div class="ladderList common_style">' +
            '                                   <div class="ladderLists first_ladderLists"> ' +
            '                                       <div class="layui-inline ladderStart">0</div><div class="layui-inline" style="color:#d9d9d9">——</div><div class="layui-inline bottom"> ' +
            '                                           <div class="custom_input "> ' +
            '                                               <input oninput="if(value > 9999999)value = 9999999;" max="9999999" maxlength="7" type="number" class="layui-input ladderEnd borderBottomLineInput"> ' +
            '                                               <div class="layui-inline unit_text ladderUite">kg</div> ' +
            '                                           </div>     ' +
            '                                       </div> ' +
            '                                       <div class="layui-inline custom_input_160 custom_input" style="width:160px;"> ' +
            '                                           <div class="lf layui-inline unit_text">用时</div> ' +
            '                                           <div class="layui-inline userTime line_height_28"> ' +
            '                                               <input oninput="if(value > 99999)value = 99999;" max="99999" maxlength="5" type="number"  class="layui-input borderBottomLineInput" value=""> ' +
            '                                           </div> ' +
            '                                           <div class="layui-inline unit_text">分钟</div> ' +
            '                                       </div> ' +
            '                                   </div> ' +
            '                               </div> ' +
            '                               <div class="ladderList layui-inline"> ' +
            '                                   <div class="ladderLists last_ladderLists"> ' +
            '                                       <div class="layui-inline custom_input_150">       ' +
            '                                           <div class="layui-inline ladderStart"></div> ' +
            '                                           <div style="" class="layui-inline ladderUite unit_text">kg以上</div> ' +
            '                                       </div> ' +
            '                                       <div class="layui-inline custom_input_160 custom_input" style="width:160px;"> ' +
            '                                           <div class="lf layui-inline unit_text">用时</div> ' +
            '                                           <div class="layui-inline userTime line_height_28"> ' +
            '                                           <input oninput="if(value > 99999)value = 99999;" max="99999" maxlength="5" type="number" class="layui-input borderBottomLineInput" value=""> ' +
            '                                           </div> ' +
            '                                           <div class="layui-inline unit_text">分钟</div> ' +
            '                                       </div> ' +
            '                                   </div> ' +
            '                                   <a class="layui-inline imgIco addIco top_5" href="javascript:;"></a> ' +
            '                               </div> ';
        $("#add_point_info_dialog .stationTimeInfoBox .ladderTimeBox .needAddLadder").html(content);
        $("#add_point_info_dialog .last_ladderLists .ladderStart").text("");
        handoverTimeType = 0; //客户交接时间类型： 1 平均时间  2阶梯时间 0无
        handoverTimeMethod = 1; //计时方式：1、重量（kg）；2、数量（件）；3、体积（m³）
        $('#add_point_info_dialog .maxVehicleType').val('')
        form.render('select');
    }

    function getStationInfo(stationInfo) {
        // AJAX(TRANSPORT_AJAX_URL + GET_STATION_INFO_URL,{
        //     stationId: stationId
        // }, function(res){
        //         if(res.code === 100){
        var obj = JSON.parse(stationInfo);
        var changeArr = {
            id: obj.id,
            stationName: judgementNull(obj.stationName),
            geography: obj.provinceName ? judgementNull(obj.provinceName) + '/' + judgementNull(obj.cityName) + '/' + judgementNull(obj.districtName) : '',
            dailAddress: judgementNull(obj.stationDetailAddress),
            areaBelong: judgementNull(obj.stationAreaName),
            receivingTimeJson: obj.receivingTimes,
            stationExcludeTimes: obj.stationExcludeTimes,
            stayTime: judgementNull(obj.stayTime),
            handOverTime: judgementNull(obj.handoverTime),
            priority: judgementNull(obj.priority),
            stationNo: judgementNull(obj.stationNo),
            maxVehicleType: judgementNull(obj.maxVehicleType),
            queueTime: judgementNull(obj.queueTime),
            stationHandoverTimeStageList: judgementNull(obj.stationHandoverTimeStageList),
            handoverTimeType: judgementNull(obj.handoverTimeType),
            handoverTimeMethod: judgementNull(obj.handoverTimeMethod)
        }
        if (obj.isKeyAccount) {
            $('input[name=isKeyAccount]').each(function () {
                if ($(this).val() == obj.isKeyAccount) {
                    $(this).prop('checked', 'checked')
                }
            })
        } else {
            $('input[name=isKeyAccount]').first().prop('checked', 'checked')
        }
        var receivingTimes = [];
        if (obj.receivingTimes != null && obj.receivingTimes.length > 0) {
            for (var k = 0; k < obj.receivingTimes.length; k++) {
                if (obj.receivingTimes[k].receivingTimeStart != null && obj.receivingTimes[k].receivingTimeStart != 'null') {
                    receivingTimes.push(obj.receivingTimes[k].receivingTimeStart + '-' + obj.receivingTimes[k].receivingTimeEnd);
                } else {
                    receivingTimes.push('');
                }
            }
        }
        var stationExcludeTimes = [];
        if (obj.stationExcludeTimes != null && obj.stationExcludeTimes.length > 0) {
            for (var k = 0; k < obj.stationExcludeTimes.length; k++) {
                if (obj.stationExcludeTimes[k].receivingTimeStart != null && obj.stationExcludeTimes[k].receivingTimeStart != 'null') {
                    stationExcludeTimes.push(obj.stationExcludeTimes[k].receivingTimeStart + '-' + obj.stationExcludeTimes[k].receivingTimeEnd);
                } else {
                    stationExcludeTimes.push('');
                }
            }
        }
        var handoverTimeObj = "";
        var handoverTimeStr = "";
        if (obj.handoverTimeType == 0) {
            handoverTimeStr = "";
        } else if (obj.handoverTimeType == 1) {
            handoverTimeStr = judgementNull(obj.handoverTime);
        } else if (obj.handoverTimeType == 2) {
            handoverTimeObj = {
                handoverTimeMethod: obj.handoverTimeMethod,
                stationHandoverTimeStageList: obj.stationHandoverTimeStageList
            };
            handoverTimeStr = "<div style='cursor:pointer;color:#0d92ef;' class='handoverTimeLookDetail' handoverTimeObj='" + JSON.stringify(handoverTimeObj) + "'>查看</div>";

        }
        var arr = changeArr;
        for (var k in arr) {
            $('.' + k).val(arr[k]);
        }
        // $('#goodsStartTime').val(arr.receivingTimeJson.length > 0 ? arr.receivingTimeJson[0].receivingTimeStart : '');
        // $('#goodsEndTime').val(arr.receivingTimeJson.length > 0 ? arr.receivingTimeJson[0].receivingTimeEnd : '');
        changeStationId = arr.id;
        if (arr.stationExcludeTimes && arr.stationExcludeTimes.length > 0) {
            $('.timeBox').html('');
            $.each(arr.stationExcludeTimes, function (i, obj) {
                var str = '<div class="unreceived_window"><div class="c-datepicker-date-editor J-datepickerTime-range datepicker-searchTime">' +
                    '<i class="c-datepicker-range__icon kxiconfont icon-clock"></i>' +
                    '<input autocomplete="off" placeholder="开始时间" class="c-datepicker-data-input c-timepicker-time-input startTime" id="startTime' + i + '" value="' + (obj.receivingTimeStart ? obj.receivingTimeStart : '') + '">' +
                    '<span class="c-datepicker-range-separator">-</span>' +
                    '<input autocomplete="off" placeholder="结束时间" class="c-datepicker-data-input c-timepicker-time-input endTime" id="endTime' + i + '" value="' + (obj.receivingTimeEnd ? obj.receivingTimeEnd : '') + '">' +
                    '</div>' +
                    '<a class="layui-inline imgIco deleIco" href="javascript:;"></a>' +
                    '<a class="layui-inline imgIco addIco" href="javascript:;"></a></div>';
                $('.timeBox').append(str);
                // $('.datepicker-searchTime').datePicker({
                //     format: 'HH:mm',
                //     isRange: true
                // });
            })
            if ($('.timeBox>div').length > 1) {
                $('.timeBox').addClass('timeBoxMore');
                $('.deleIco').css('display', 'inline-block');
                $('.addIco').hide();
                $('.timeBox>div:last-child .addIco').show();
            }
            $('.listTime').height($('.timeBox').height());
        }
        var st = '<div class="c-datepicker-date-editor J-datepickerTime-range datepicker-searchTime-open">' +
            '                                        <i class="c-datepicker-range__icon kxiconfont icon-clock"></i>' +
            '                                        <input autocomplete="off" placeholder="开始时间" class="c-datepicker-data-input c-timepicker-time-input startTime" id="goodsStartTime" value="' +
            ((arr.receivingTimeJson && arr.receivingTimeJson.length) > 0 ? (arr.receivingTimeJson[0].receivingTimeStart || '') : '') + '">' +
            '                                        <span class="c-datepicker-range-separator">-</span>' +
            '                                        <input autocomplete="off" placeholder="结束时间" class="c-datepicker-data-input c-timepicker-time-input endTime" id="goodsEndTime" value="' +
            ((arr.receivingTimeJson && arr.receivingTimeJson.length) > 0 ? (arr.receivingTimeJson[0].receivingTimeEnd || '') : '') + '">' +
            '                                    </div>'
        $('.timeBox1 > div').html(st);
        $(".maxVehicleType").val(arr.maxVehicleType);
        $('.open-window input:radio').each(function (index, el) {
            el.checked = false;
        });
        if (arr.handoverTimeType == 2) {
            handoverTimeType = 2;
            if (arr.stationHandoverTimeStageList) {
                var len = arr.stationHandoverTimeStageList.length;
                $(".first_ladderLists").find(".ladderStart").text(arr.stationHandoverTimeStageList[0].smallIntervalStage);

                $(".first_ladderLists").find(".ladderEnd").val(arr.stationHandoverTimeStageList[0].largeIntervalStage);

                $(".first_ladderLists").find(".userTime>input").val(arr.stationHandoverTimeStageList[0].time);

                $(".last_ladderLists").find(".ladderStart").text(arr.stationHandoverTimeStageList[len - 1].smallIntervalStage);

                $(".last_ladderLists").find(".userTime>input").val(arr.stationHandoverTimeStageList[len - 1].time);
                if (len > 2) {
                    for (var idx = 1; idx < arr.stationHandoverTimeStageList.length - 1; idx++) {
                        var str = '<div class="ladderList min_ladderLists common_style">' +
                            '<div class="ladderLists first_ladderLists">' +
                            '<div class="layui-inline ladderStart">' + arr.stationHandoverTimeStageList[idx].smallIntervalStage + '</div><div class="layui-inline" style="color:#d9d9d9">——</div><div class="layui-inline bottom">' +
                            '<div class="custom_input ">' +
                            '<input value=' + arr.stationHandoverTimeStageList[idx].largeIntervalStage + ' oninput="if(value > 9999999)value = 9999999;" max="9999999" maxlength="7" type="number" class="layui-input ladderEnd borderBottomLineInput">' +
                            '<div class="layui-inline unit_text ladderUite">kg</div>' +
                            '            </div> ' +
                            '        </div> ' +
                            '        <div class="layui-inline custom_input_160 custom_input" style="width:160px;"> ' +
                            '            <div class="lf layui-inline unit_text">用时</div> ' +
                            '            <div class="layui-inline userTime line_height_28"> ' +
                            '                <input value="' + arr.stationHandoverTimeStageList[idx].time + '" oninput="if(value > 99999)value = 99999;" max="99999" maxlength="5" type="number"  class="layui-input borderBottomLineInput" value=""> ' +
                            '            </div> ' +
                            '            <div class="layui-inline unit_text">分钟</div> ' +
                            '        </div> ' +
                            '    </div> ' +
                            '<a class="layui-inline imgIco deleIco top_5" href="javascript:;"></a>' +
                            '</div>';

                        $('.ladderList.common_style').last().after(str)
                    }
                }
            }
            handoverTimeMethod = arr.handoverTimeMethod ? arr.handoverTimeMethod : 1;
            var ladderUite = "";
            $(".jietiTime").prop("checked", true);
            switch (handoverTimeMethod) {
                case 1:
                    ladderUite = "kg";
                    $(".typeWeight").prop("checked", true);
                    break;
                case 2:
                    ladderUite = "件";
                    $(".typeNumber").prop("checked", true);
                    break;
                case 3:
                    ladderUite = "m³";
                    $(".typeVolume").prop("checked", true);
                    break;
                default:
                    break;
            }
            $(".ladderUite").text(ladderUite);
            $(".ladderTimeBox").show();
            $(".handOverTimeBox").hide();
            $(".handOverTime").val("");
        } else if (arr.handoverTimeType == 1) {
            handoverTimeType = 1;
            $(".typeWeight").prop("checked", true)
            $(".pingjunTime").prop("checked", true);
            $(".handOverTimeBox").show();
            $(".ladderTimeBox").hide();
            $(".handOverTime").val(arr.handOverTime);
            $(".min_ladderLists").remove();
        } else if (arr.handoverTimeType == 0) {
            handoverTimeType = 0;
            $(".noTime").prop("checked", true);
        }
        form.render();
        //         }
        //     }
        // )
    }
    function getMaxVehicleTypeListBack(res) {
        if (res.code == 100) {
            var str = "<option value=''>" + "请选择" + "</option>";
            for (var i = 0; i < res.result.length; i++) {
                str += "<option value=" + res.result[i] + ">" + res.result[i] + "</option>"
            }
            $(".maxVehicleType").html(str)
            form.render()
        } else {
            layer.msg(res.msg, { time: 1500 });
        }
    }

    // 收货时间选择器
    $('.timeBox1').on('click', '.datepicker-searchTime-open', function (e) {
        e.stopPropagation();
        new RangeTimePicker(e, null, { validate: true });
    })
    //不收货时间控件
    $('.addStationCont').on('click', '.datepicker-searchTime', function (e) {
        e.stopPropagation();
        new RangeTimePicker(e, null, { validate: true });
    })

    var timeIndex = 10;

    //添加时间
    $('.timeBox').on('click', '.addIco', function () {
        if ($(this).parent().find('.c-datepicker-data-input').val() == '') {
            layer.msg('请先选择时间', { time: 1500 });
            return false;
        }
        timeIndex++;
        var str = '<div class="unreceived_window">' +
            '<div class="c-datepicker-date-editor J-datepickerTime-range datepicker-searchTime">' +
            '<i class="c-datepicker-range__icon kxiconfont icon-clock"></i>' +
            '<input placeholder="开始时间" class="c-datepicker-data-input c-timepicker-time-input startTime" id="startTime' + timeIndex + '">' +
            '<span class="c-datepicker-range-separator">-</span>' +
            '<input placeholder="结束时间" class="c-datepicker-data-input c-timepicker-time-input endTime" id="endTime' + timeIndex + '">' +
            '</div>' +
            '<a class="layui-inline imgIco deleIco" href="javascript:;"></a>' +
            '<a class="layui-inline imgIco addIco" href="javascript:;"></a></div>';
        $('.timeBox').append(str);
        // $('.datepicker-searchTime').datePicker({
        //     format: 'HH:mm',
        //     isRange: true
        // });
        if ($('.timeBox>div').length > 1) {
            $('.timeBox').addClass('timeBoxMore');
            $('.deleIco:not(.top_5)').css('display', 'inline-block');
            $('.addIco:not(.top_5)').hide();
            $('.timeBox>div:last-child .addIco').show();
        }
        $('.listTime').height($('.timeBox').height());
    })
    //删除时间
    $('.timeBox').on('click', '.deleIco', function () {
        $(this).parent().remove();
        $('.listTime').height($('.timeBox').height());
        $('.addIco:not(.top_5)').hide();
        $('.timeBox>div:last-child .addIco').show();
        if ($('.timeBox>div').length == 1) {
            $('.timeBox').removeClass('timeBoxMore');
            $('.deleIco:not(.top_5)').hide();
        }
    });

    //输入地址
    $('#add_point_info_dialog .dailAddress').change(function () {
        //调用高德地图
        AJAX('//restapi.amap.com/v3/geocode/geo?parameters', { key: '11ca106404a51e3f04745c2f710d18c0', address: $(this).val() }, dailAddressBack)
    });
    function dailAddressBack(res) {
        if (res.geocodes && res.geocodes.length > 0) {
            var obj = res.geocodes[0]
            longitude = obj.location.split(',')[0];//分割字符串
            latitude = obj.location.split(',')[1];//分割字符串
            $('#add_point_info_dialog .geography').val(obj.province + '/' + obj.city + '/' + obj.district)
        } else {
            $('#add_point_info_dialog .geography').val('')
            // layer.msg('该地址不存在',{
            //     time:1000
            // })
            // return;
        }
    }

    //站点匹配分区
    $('#add_point_info_dialog .dailAddress').change(function () {
        var _this = $(this);
        if ($(this).val() != '') {
            AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/stationArea/matchArea', { detailAddress: _this.val() }, dailBack)
        }
    })
    function dailBack(res) {
        if (res.code == 100) {
            $('#add_point_info_dialog .areaBelong').val(res.result.name);
        } else {
            $('#add_point_info_dialog .areaBelong').val('');
        }
    }
    var handoverTimeType = 0; //客户交接时间类型： 1 平均时间  2阶梯时间 0无
    /* 客户交接时间类型： */
    form.on('select(handoverTimeType)', function (data) {
        if (data.value == 1) {
            $(".ladderTimeBox").hide();
            $(".handOverTimeBox").show();
        } else if (data.value == 2) {
            $(".handOverTimeBox").hide();
            $(".ladderTimeBox").show();
            $(".typeWeight").prop("checked", true);
            handoverTimeMethod = 1;
            $(".ladderUite").text("kg");
            form.render('select');
        } else if (data.value == 0) {
            $(".handOverTimeBox").hide();
            $(".ladderTimeBox").hide();
        }
        handoverTimeType = data.value;
    })
    /* 计时方式： */
    form.on('select(handoverTimeMethod)', function (data) {
        if (data.value == 1) {
            $(".ladderUite").html("kg")
        } else if (data.value == 2) {
            $(".ladderUite").html("件")
        } else if (data.value == 3) {
            $(".ladderUite").html("m³")
        }
        handoverTimeMethod = data.value;
    })
    //确定添加或修改站点
    $('#add_point_info_dialog').on('click', '.submit_btn,.update_btn', function () {
        if ($('.dailAddress').val() == '') {
            layer.msg('请填写详细地址', { time: 1500 });
            return
        }
        loading = layer.msg('请等待！', {
            icon: 16
            , shade: 0.01
            , time: false
        });
        var url = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/station/add';
        var data = {
            provinceName: $('#add_point_info_dialog .geography').val().split('/')[0],    //省
            cityName: $('#add_point_info_dialog .geography').val().split('/')[1],    //市
            districtName: $('#add_point_info_dialog .geography').val().split('/')[2],    //区
            stationName: $('#add_point_info_dialog .stationName').val(),        //站点名
            stationDetailAddress: $('#add_point_info_dialog .dailAddress').val(),    //站点地址
            stayTime: $('#add_point_info_dialog .stayTime').val(),   //允许停留时间
            priority: $('#add_point_info_dialog .priority').val(),    //优先级
            stationNo: $('#add_point_info_dialog .stationNo').val(), // 编号
            maxVehicleType: $('#add_point_info_dialog .maxVehicleType').val(),
            queueTime: $('#add_point_info_dialog .queueTime').val(),
            isKeyAccount: $('#add_point_info_dialog input[name=isKeyAccount]:checked').val(),
        };
        var receivingTimeJson;
        if ($('#goodsStartTime').val() && $('#goodsEndTime').val()) {
            receivingTimeJson = [{
                receivingTimeStart: $('#goodsStartTime').val(),
                receivingTimeEnd: $('#goodsEndTime').val(),
            }];
        }
        data.receivingTimeJson = receivingTimeJson ? JSON.stringify(receivingTimeJson) : null;
        var stationExcludeTimes = [];
        $.each($('.timeBox>div'), function () {
            if ($(this).find('.startTime').val() != '' && $(this).find('.endTime').val() != '') {
                var data1 = {
                    receivingTimeStart: $(this).find('.startTime').val(),
                    receivingTimeEnd: $(this).find('.endTime').val()
                };
                stationExcludeTimes.push(data1);
            }
        });
        if (stationExcludeTimes.length > 0) {
            data.excludeTimeJson = JSON.stringify(stationExcludeTimes);
        }
        if ($(this).hasClass('updatastation')) {
            url = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/station/update';
            data.id = changeStationId;
        }
        if ($(this).hasClass('update_btn')) {
            url = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/station/update';
            data.id = changeStationId;
        }
        var stationHandoverTimeStageJsonArr = [];
        if (handoverTimeType == 1) {
            if ($("#add_point_info_dialog .handOverTime").val() != "") {
                data.handoverTime = $("#add_point_info_dialog .handOverTime").val();
                data.handoverTimeType = handoverTimeType;
            } else {
                de
                layer.msg("交接货时长不能为空");
                return false;
            }
        } else if (handoverTimeType == 2) {
            var isBigNum = -1;
            var isFlag = true;
            if ($(".first_ladderLists").find(".ladderStart").text() != '' && $(".first_ladderLists").find(".userTime>input").val() != '') {
                stationHandoverTimeStageJsonArr.push({
                    smallIntervalStage: $(".first_ladderLists").find(".ladderStart").text() * 1,
                    time: $(".first_ladderLists").find(".userTime>input").val() * 1
                })
            } else {
                isFlag = false;
            }
            if ($(".min_ladderLists").length > 0) {
                $.each($(".min_ladderLists"), function () {
                    if ($(this).find(".ladderStart").text() != '' && $(this).find(".userTime>input").val() != '') {
                        stationHandoverTimeStageJsonArr.push({
                            smallIntervalStage: $(this).find(".ladderStart").text() * 1,
                            time: $(this).find(".userTime>input").val() * 1
                        })
                    } else {
                        isFlag = false;
                    }
                })
            }
            if ($(".last_ladderLists").find(".ladderStart").text() != '' && $(".last_ladderLists").find(".userTime>input").val() != '') {
                stationHandoverTimeStageJsonArr.push({
                    smallIntervalStage: $(".last_ladderLists").find(".ladderStart").text() * 1,
                    time: $(".last_ladderLists").find(".userTime>input").val() * 1
                })
            } else {
                isFlag = false;
            }
            data.handoverTimeType = handoverTimeType;
            data.handoverTimeMethod = handoverTimeMethod;
            data.stationHandoverTimeStageJson = JSON.stringify(stationHandoverTimeStageJsonArr);
            $.each($(".ladderEnd"), function () {
                if (Number($(this).val()) > Number(isBigNum)) {
                    isBigNum = Number($(this).val());
                } else {
                    isFlag = false;
                }
            })
            if (!isFlag) {
                layer.msg("单位数值、时间有误")
                return false;
            }
        } else if (handoverTimeType == 0) {
            data.handoverTimeType = handoverTimeType;
        }
        AJAX(url, data, saveAreaBack);
    })

    function saveAreaBack(res) {
        layer.close(loading)
        if (res.code == 100) {
            layer.msg('成功', { time: 500 });
            $('#add_point_info_dialog').hide();
            clearStationInput();
            getTasksList()
        } else {
            layer.msg(res.msg, { time: 3000 });
        }
    }

    $('#add_point_info_dialog .dialog_close').click(function () {
        clearStationInput()
    })


    /* 阶梯时间添加 */
    $(".ladderListBox").on('click', '.addIco', function () {
        if ($(".min_ladderLists").length > 0) {
            if ($(".min_ladderLists").eq($(".min_ladderLists").length - 1).find(".ladderEnd").val() == "") {
                layer.msg("请输入计数");
                return false;
            }
            if ($(".min_ladderLists").eq($(".min_ladderLists").length - 1).find(".userTime input").val() == "") {
                layer.msg("请输入时间");
                return false;
            }
        } else {
            if ($(".min_ladderLists").length == 0 && $(".first_ladderLists .ladderEnd").val() == "") {
                layer.msg("请输入计数");
                return false;
            }
            if ($(".first_ladderLists .userTime input").val() == "") {
                layer.msg("请输入时间");
                return false;
            }
        }//zzz
        var str = '<div class="ladderList min_ladderLists common_style">' +
            '<div class="ladderLists first_ladderLists">' +
            '<div class="layui-inline ladderStart">0</div><div class="layui-inline" style="color:#d9d9d9">——</div><div class="layui-inline bottom">' +
            '<div class="custom_input ">' +
            '<input oninput="if(value > 9999999)value = 9999999;" max="9999999" maxlength="7" type="number" class="layui-input ladderEnd borderBottomLineInput">' +
            '<div class="layui-inline unit_text ladderUite">kg</div>' +
            '            </div> ' +
            '        </div> ' +
            '        <div class="layui-inline custom_input_160 custom_input" style="width:160px;"> ' +
            '            <div class="lf layui-inline unit_text">用时</div> ' +
            '            <div class="layui-inline userTime line_height_28"> ' +
            '                <input oninput="if(value > 99999)value = 99999;" max="99999" maxlength="5" type="number"  class="layui-input borderBottomLineInput" value=""> ' +
            '            </div> ' +
            '            <div class="layui-inline unit_text">分钟</div> ' +
            '        </div> ' +
            '    </div> ' +
            '<a class="layui-inline imgIco deleIco top_5" href="javascript:;"></a>' +
            '</div>';

        $('.ladderList.common_style').last().after(str)
        $(".stationTimeInfoBox").scrollTop($(".stationTimeInfoBox").height() + $(".stationTimeInfoBox").scrollTop());
        var $min_lad_list = $(".min_ladderLists");
        if ($min_lad_list.length == 1) {
            $min_lad_list.eq(0).find(".ladderStart").text($(".first_ladderLists .ladderEnd").val());
        } else if ($(".min_ladderLists").length > 1) {
            $min_lad_list.eq($min_lad_list.length - 1).find(".ladderStart").text($min_lad_list.eq($min_lad_list.length - 2).find(".ladderEnd").val())
        }
    })
    /* 单位数量失焦事件 */
    $(".needAddLadder").on("blur", ".ladderEnd", function () {
        var $min_ladderLists = $(this).parents('.ladderList');
        if ($(this).val() && $min_ladderLists.find(".ladderStart").text() && $(this).val() * 1 <= $min_ladderLists.find(".ladderStart").text() * 1) {
            layer.msg("该数值需要大于" + $min_ladderLists.find(".ladderStart").text())
            $(this).val("")
            return false;
        }
        if ($(this).parents('.ladderList').index() == $(".min_ladderLists").find(".ladderEnd").length) {
            $(".last_ladderLists").find(".ladderStart").text($(this).val());
            return false;
        } else {
            $(".min_ladderLists").eq($(this).parents('.ladderList').index()).find(".ladderStart").text($(this).val());
            return false;
        }
    })
    /* 阶梯时间删除 */
    $(".ladderListBox").on("click", ".deleIco", function () {
        var index = $(this).parent().index();
        if ($(".min_ladderLists").length > 1) {
            $(".last_ladderLists").find(".ladderStart").text($(".min_ladderLists").eq($(".min_ladderLists").length - 1).find(".ladderEnd").val());
            if (index == ($(".min_ladderLists").length - 1)) {
                $(".last_ladderLists").find(".ladderStart").text($(".min_ladderLists").eq(index - 1).find(".ladderEnd").val());
            } else if (index == 0) {
                $(".min_ladderLists").eq(1).find(".ladderStart").text($(".first_ladderLists .ladderEnd").val())
            } else {
                $(".min_ladderLists").eq(index + 1).find(".ladderStart").text($(".min_ladderLists").eq(index - 1).find(".ladderEnd").val())
            }
        } else {
            $(".last_ladderLists").find(".ladderStart").text($(".first_ladderLists .ladderEnd").val());
        }
        $(this).parent().remove();
    })
    $('#add_point_info_dialog').on('click', '.maxVehicleType+.layui-form-select', function () {
        setTimeout(function () {
            $('.addStationCont').scrollTop($('.addStationCont').prop("scrollHeight"));
        }, 0)
    })
    /* 单位数量失焦事件 */
    $(".first_ladderLists").on("blur", ".ladderEnd", function () {
        if ($(".min_ladderLists").length > 0) {
            $(".min_ladderLists").eq(0).find(".ladderStart").text($(this).val())
        } else {
            $(".last_ladderLists").find(".ladderStart").text($(this).val())
        }
    })
    $('#add_point_info_dialog .sm_sort_btn').on('click', function () {
        var menu_id = '';
        My_XQ_Menu_Data.forEach(function (item) {
            if (item.url == '/transport/vehicleType') {
                menu_id = item.id;
            }
        })
        window.open('/transport/vehicleType?menu_click_id=' + menu_id + '&scrollTop=0&sort=true', "_blank");
    })

}

// 极速排线
$('#fast_plan_route').click(function () {
    if (!operateCkecked.getIDS()) {
        layer.msg('请选择运单！', { time: 1800 });
        return false
    }
    var menu_id = '9955';
    if (My_XQ_Menu_Data.length > 0) {
        My_XQ_Menu_Data.forEach(function (item) {
            if (item.url == '/transport/new_ManualPlanOrder') {
                menu_id = item.id;
            }
        })
    }
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/order/getByOrderNos',
        {
            orderNos: operateCkecked.getIDS(),
            pageNum: 1,
            pageSize: 0
        },
        function (res) {
            if (res.code == 100) {
                var startTime = 0;
                var endTime = 0;
                res.result.forEach(function (item) {
                    if (item.expectedDeliveryStartTime < startTime || !startTime) {
                        startTime = item.expectedDeliveryStartTime;
                    }
                    if (item.expectedDeliveryEndTime > endTime || !endTime) {
                        endTime = item.expectedDeliveryEndTime;
                    }
                })
                var time = time = '&startTime=' + startTime + '&endTime=' + endTime;
                sessionStorage.setItem('manualIds', operateCkecked.getIDS());
                window.location = '/transport/new_ManualPlanOrder?menu_click_id=' + menu_id + '&scrollTop=0&showParams=true' + time;
            } else {
                layer.msg(res.msg, { time: 1800 });
            }
        })
})

$('.addBTTn').on('click', function () {
    renderNewModelTable([], false)
    $('.new_dialog').show()
    $('.open-window1').hide()
    $('.whatNewName').text('新建模板')
    form.val("exampleCablearr", {
        "cablearr": "intelligence"
    })
    arr = []
    renderNewModelTable([], 1)
})
$('.close_new_model').on('click', function () {
    $('.new_dialog').hide()
    myTemplateID = ''
    arr = []
    $("input[name='cablearr'][value=intelligence]").attr("disabled", false);
    $("input[name='cablearr'][value=intelligence]").next().removeClass('layui-radio-disbaled layui-disabled');
    $("input[name='cablearr'][value=hands]").attr("disabled", false);
    $("input[name='cablearr'][value=hands]").next().removeClass('layui-radio-disbaled layui-disabled');
    $('.open-window1').show()
    $('.new_dialog_content .dialog_body_son .layui-input').val('')

})

// 新建模板表头 window.parent.location.reload();
var arr = []
var moren = 1;

function renderNewModelTable(array, moren, newarr) {
    moren = moren;
    var newModelHead = [[ // 表头
        // { field: 'td1', title: '模板列名', width: '208', },
        // { field: 'td2', title: '自定义列名', edit: 'text', width: '227' },
        // { field: 'td3', title: '说明', width: '783' },
        // { field: 'td4', title: '删除', width: '60' }, templet: '#typecolor'
        { field: 'td1', title: '模板列名', width: '20%', },
        {
            field: 'td2', title: '自定义列名', edit: 'text', width: '20%', style: 'color:#999',
        },
        { field: 'td3', title: '说明', width: '50%', style: 'color:#999' },
        { field: 'td4', title: '删除', width: '8%', },
    ]];

    var newModelBody = []
    var headArray1 = [{
        id: 1013,
        ismust: 'is',
        name: '发货地址',
        reWriteliName: '发货地址',
        reWriteliName1: '发货地址',
        keyName: 'originAddress',
        discripton: '',
    }, {
        id: 1012,
        ismust: 'is',
        name: '收货地址',
        reWriteliName: '收货地址',
        reWriteliName1: '收货地址',
        keyName: 'detailAddress',
        discripton: '',
    }, {
        id: 1011,
        ismust: 'is',
        name: '下单时间',
        reWriteliName: '下单时间',
        reWriteliName1: '下单时间',
        keyName: 'orderTime',
        discripton: '指客户的下单时间或生成运单的时间;格式为：2018-01-01 08:00',
    }, {
        id: 1010,
        ismust: 'is',
        name: '期望送达时间起',
        reWriteliName: '期望送达时间起',
        reWriteliName1: '期望送达时间起',
        keyName: 'expectedDeliveryStartTime',
        discripton: '货物期望送达的最早时间窗口;格式为：2018-01-01 08:00',
    }, {
        id: 1009,
        ismust: 'is',
        name: '期望送达时间止',
        reWriteliName: '期望送达时间止',
        reWriteliName1: '期望送达时间止',
        keyName: 'expectedDeliveryEndTime',
        discripton: '货物期望送达的最晚时间窗口;格式为：2018-01-01 08:00',
    }, {
        id: 1008,
        ismust: 'is',
        name: '商品数量',
        reWriteliName: '商品数量',
        reWriteliName1: '商品数量',
        keyName: 'quantity',
        discripton: '',
    }, {
        id: 1007,
        ismust: 'is',
        name: '商品总体积',
        reWriteliName: '商品总体积(m3)',
        reWriteliName1: '商品总体积(m3)',
        keyName: 'volume',
        discripton: '',
    },
    {
        id: 1006,
        ismust: 'is',
        name: '商品总重量',
        reWriteliName: '商品总重量(kg)',
        reWriteliName1: '商品总重量(kg)',
        keyName: 'load',
        discripton: ''
    }]
    var headArray2 = [{
        id: 1005,
        ismust: 'is',
        name: '发货地址',
        reWriteliName: '发货地址',
        reWriteliName1: '发货地址',
        keyName: 'originAddress',
        discripton: '',
    },
    {
        id: 1004,
        ismust: 'is',
        name: '收货地址',
        reWriteliName: '收货地址',
        reWriteliName1: '收货地址',
        keyName: 'detailAddress',
        discripton: '',
    }, {
        id: 1003,
        istuijian: 'is',
        name: '商品数量',
        reWriteliName: '商品数量',
        reWriteliName1: '商品数量',
        keyName: 'quantity',
        discripton: '',
    }, {
        id: 1002,
        istuijian: 'is',
        name: '商品总体积',
        reWriteliName: '商品总体积(m3)',
        reWriteliName1: '商品总体积(m3)',
        keyName: 'volume',
        discripton: '',
    }, {
        id: 1001,
        istuijian: 'is',
        name: '商品总重量',
        reWriteliName: '商品总重量(kg)',
        reWriteliName1: '商品总重量(kg)',
        keyName: 'load',
        discripton: '',
    }]
    // console.log('9999前', arr)
    if (arr.length === 0) {
        if (moren === 1) { arr = headArray1 }
        if (moren === 2) { arr = headArray2 }
    } else if (arr.length === 0 && array.length === 0) {
        if (moren === 1) { arr = headArray1 }
        if (moren === 2) { arr = headArray2 }
    }
    if (moren === 2 && newarr) {
        arr = []
        newarr.forEach(function (item) {
            if (item.ismust || item.istuijian) {
                arr.push(item)
            }
        })
    } else if (moren !== 2 && newarr) {
        // console.log('不等于2')
        arr = []
        newarr.forEach(function (item) {
            if (item.ismust || item.istuijian) {
                arr.push(item)
            }
        })
    }
    arr = arr.concat(array)
    //
    //
    var obj = {}; // 旧模板处理
    arr = arr.reduce(function (item, next) {
        if (!next || !item) {
        } else {
            obj[next.keyName] ? '' : obj[next.keyName] = true && item.push(next);
        }
        return item;
    }, [])
    // console.log('后', arr)

    arr = getSsort(arr);
    arr.forEach(function (item) {
        var addStr = (item.ismust ? '<span style="color:red">（必填）<span>' : (item.istuijian ? '<span style="color:#FF8E34">（推荐）<span>' : '<span style="color:#999999">（选填）<span>'))
        newModelBody.push({
            td1: item.reWriteliName1 ? item.reWriteliName1 + addStr : '',
            td2: item.reWriteliName ? item.reWriteliName : '',
            // td2: item,
            td3: item.discripton ? item.discripton : '',
            td4: item.ismust ? "<button class='layui-btn bull' type='button' lay-event='del' disabled style='color:#999999;border-bottom:none' lay-filter='delete_btn' data-id='" + item.id + "'>删除</button>" : "<button class='layui-btn bull' type='button' style='border-bottom:none' lay-event='del'  lay-filter='delete_btn' data-id='" + item.id + "'>删除</button>"

        });
    })
    tableList2('tableCont', newModelHead, null, newModelBody, '400');
    setTimeout(function () {
        table.reload('tableCont')
        var myEvent = new Event('resize');
        window.dispatchEvent(myEvent);
        table.resize('tableCont'); //重置表格尺寸
    }, 0)
}
// 序列
function getSsort(arr) {
    for (var j = 0; j < arr.length - 1; j++) {
        for (var i = 0; i < arr.length - 1 - j; i++) {
            if (arr[i].id < arr[i + 1].id) {
                var temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
    }
    return arr
}

// 修改模板
var allModelList = []; // 所有模板字段
$('#tempIdOne').on('click', '.eidt', function () {
    $('.whatNewName').text('编辑模板')
    var id = $(this)[0].dataset.id;
    var obj = getModelList(id)
    $('.new_dialog').show()
    $('.open-window1').hide()
    // console.log(obj)
    var type = 2;
    $('.new_dialog_content .dialog_body_son .layui-input').val(obj.templateName)
    if (obj.detailAddress && obj.expectedDeliveryEndTime && obj.expectedDeliveryStartTime && obj.orderTime && obj.originAddress && obj.quantity && obj.volume) {
        type = 0
        form.val("exampleCablearr", {
            "cablearr": "intelligence"
        })
        // form.render();
    } else {
        type = 1
        form.val("exampleCablearr", {
            "cablearr": "hands"
        })
    }
    $("input[name='cablearr'][value=intelligence]").attr("disabled", "disabled");
    $("input[name='cablearr'][value=intelligence]").next().addClass('layui-radio-disbaled layui-disabled');
    $("input[name='cablearr'][value=hands]").attr("disabled", "disabled");
    $("input[name='cablearr'][value=hands]").next().addClass('layui-radio-disbaled layui-disabled');
    var arr = reSetObjToArray(obj, type)
    // console.log(arr)
    renderNewModelTable(arr, true)
})
function getModelList(id) {
    var iten
    // console.log(id)
    myTemplateID = id;
    allModelList.forEach(function (item) {
        if (+item.id === +id) {
            iten = item
        }
    })
    return iten
}
// 下载模板
$('#tempIdOne').on('click', '.downloda', function () {
    var id = +$(this)[0].dataset.id;
    // var confirmText = '<div class="confirm_content">该样板数据仅供测试，实际使用前，请将其取消！</div>' +
    //     '<div class="confirm_tips">是否导入样板运单？</div>';
    var confirmText = '<div class="confirm_tips">是否删除该模板？</div>';
    layer.confirm(confirmText, {
        title: '<span class="confirm_tips_title">温馨提示</span>',
        // closeBtn : true,
        btn: ['确定', '取消'],
        area: ['auto', 'auto'],
        shade: .5,

    }, function (index) {
        layer.close(index);
        // console.log(id)
        AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/mappingTemplate/deleteById', 'id=' + id, function (res) {
            if (res.code === 100) {
                layer.msg('删除成功', { time: 1500 });
                getTransportInfoList()
                arr = [];
                moren = 1;
                myTemplateID = ''; // 模板id
                $("input[name='cablearr'][value=intelligence]").attr("disabled", false);
                $("input[name='cablearr'][value=intelligence]").next().removeClass('layui-radio-disbaled layui-disabled');
                $("input[name='cablearr'][value=hands]").attr("disabled", false);
                $("input[name='cablearr'][value=hands]").next().removeClass('layui-radio-disbaled layui-disabled');
            } else {
                layer.msg(res.result, { time: 1500 });
            }

        })
    })

})
// 删除模板
$('#tempIdOne').on('click', '.del', function () {
    var id = +$(this)[0].dataset.id;
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/mappingTemplate/downLoadTemp', 'id=' + id, function (res) {
        if (res.code === 100) {
            // window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/file?filename=' + encodeURI(exl.fileName);
            window.location.href = TRANSPORT_AJAX_URL + '/xq-route-plan-tms/download/file?filename=' + res.result;
        }

    })
})
// 监听单选框的值
form.on('radio(cablearr)', function (data) {
    arr = []
    moren = data.value === "intelligence" ? 1 : 2
    form.render();
    if (myTemplateID === '' && arr.length === 0) {
        renderNewModelTable([], moren)
    } else if (myTemplateID !== '' && arr.length !== 0) {
        renderNewModelTable(arr, moren)
    } else {
        renderNewModelTable([], moren)
    }
    // console.log(moren)
})
// 确定新建模板按钮
$('.new_update_btn').on('click', function () {
    var newObj = {}
    var tempName = $('.new_dialog_content .dialog_body_son .layui-input').val().trim()
    // console.log(tempName)
    arr.forEach(function (item) {
        newObj[item.keyName] = item.reWriteliName
    })
    // console.log(newObj)
    // console.log(tempName)
    if (tempName === '') {
        layer.msg('请输入模板名称')
        return
    } else if (tempName.length > 10) {
        layer.msg('模板名称不能超过十个字')
        return
    } else {
        newObj.templateName = tempName
    } if (myTemplateID !== '') {
        newObj.id = myTemplateID;
    }
    // console.log(moren)
    if (moren === 1) {
        newObj.templateType = 1;
    } else {
        newObj.templateType = 2;
    }
    // myTemplateID = '';
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/mappingTemplate/saveOrUpdate', newObj, getResRetrun)

})
function getResRetrun(res) {
    if (res.code === 100) {
        if (myTemplateID === '') {
            layer.msg('保存成功', { time: 1500 });
        } else {
            layer.msg('保存成功', { time: 1500 });
        }
        myTemplateID = '';
        moren = 1; // 默认智能
        arr = []
        $("input[name='cablearr'][value=intelligence]").attr("disabled", false);
        $("input[name='cablearr'][value=intelligence]").next().removeClass('layui-radio-disbaled layui-disabled');
        $("input[name='cablearr'][value=hands]").attr("disabled", false);
        $("input[name='cablearr'][value=hands]").next().removeClass('layui-radio-disbaled layui-disabled');
        $('.new_dialog').hide()
        $('.open-window1').show()
        getTransportInfoList()
        $('.new_dialog_content .dialog_body_son .layui-input').val('')
    } else {
        layer.msg(res.msg, { time: 1500 });
    }
}
// 删除行
table.on('tool(test)', function (obj) {
    // console.log($(obj.data.td4)[0].dataset.id)
    // console.log(arr)
    var id = +$(obj.data.td4)[0].dataset.id
    layer.confirm('真的删除该行么？', function (index) {
        // console.log(obj)
        obj.del();
        var delArray = []
        arr.forEach(function (item) {
            // console.log(item, id)
            if (item.id !== id) {
                delArray.push(item)
            }
        })
        arr = '';
        arr = delArray;
        // console.log(arr)
        // renderNewModelTable(arr, true)
        layer.close(index);
    });
})
//监听单元格编辑111
table.on('edit(test)', function (obj) {
    var id = +$(obj.data.td4)[0].dataset.id
    //修改前的值
    // console.log(obj)
    var oldValue = $(this).prev().text();
    var value = obj.value.trim() //得到修改后的值
        , data = obj.data.td4 //得到所在行所有键值
        , field = obj.field; //得到字段

    if (value === '') {
        layer.msg('列名不能为空！');
        $(this).val(oldValue)
        return
    } else {
        arr.forEach(function (item) {
            if (item.id === id) {
                item.reWriteliName = value
            }
        })
        // renderNewModelTable(arr, true)
    }
});
//监听单元格编辑2222
var tempArray1 = []
table.on('edit(test1)', function (obj) {
    var obj1 = JSON.parse($(obj.data.td4)[0].value)
    //修改前的值
    // console.log(obj1)
    var oldValue = $(this).prev().text();
    var value = obj.value.trim() //得到修改后的值
        , data = obj.data.td4 //得到所在行所有键值
        , field = obj.field; //得到字段
    // console.log(value)
    if (value === '') {
        layer.msg('列名不能为空！');
        $(this).val(oldValue)
        return
    } else {
        obj1.reWriteliName = value;
        $('#yin' + obj1.id).val(JSON.stringify(obj1))
        // arr.forEach(function (item) {
        //     if (item.id === id) {
        //         item.reWriteliName = value
        //     }
        // })
        // renderNewModelTable(arr, true)
    }
});
// 点击添加列名
$('.addColumn').on('click', function () {
    if (myTemplateID === '') {
        rendreTable2()
    } else {
        rendreTable2()
    }
    removeCheckedInput()
    var arrArry = []
    var thatArry = []
    var chekedList = $('.new_dialog_content1 .layui-table-body tbody tr td input');
    chekedList.each(function () {
        var obj = JSON.parse(this.value)
        var that = $(this).next();
        thatArry.push(that)
        arrArry.push(obj);
    });
    arrArry.forEach(function (item1, index) {
        thatArry[index].addClass(item1.id + "")
        checkIdsIsIn(item1, thatArry[index])
    })
    // console.log(arr)
    $('.new_dialog').hide()
    $('.new_dialog1').show()
})

function checkIdsIsIn(iten, e) {
    var idList = []
    arr.forEach(function (item) {
        idList.push(item.id)
    })
    idList.forEach(function (item) {
        $('.' + item).prev().prop('checked', true)
        $('.' + item).addClass('layui-form-checked')
    })

}
rendreTable2()
function rendreTable2() {
    // 添加列名表头
    var newModelHead1 = [[
        { field: 'td1', title: '分类', merge: true, width: '10%', },
        { field: 'td2', title: '模板名', width: '15%' },
        { field: 'td5', title: '自定义列名', width: '15%', edit: 'text' }, //#e2e2e2
        { field: 'td3', title: '说明', width: '50%' },
        { field: 'td4', title: '选择', width: '8%', },
    ]];
    // 添加列名数据
    var arr1 = [{
        id: 41,
        name: '地址信息',
        reWriteliName: '片区号',
        reWriteliName1: '片区号',
        keyName: 'areaName',
        discripton: '配送订单时的线路号，在规划线路按片区运营时可根据片区号进行规划'
    },
    {
        id: 40,
        name: '地址信息',
        reWriteliName: '提货地址',
        reWriteliName1: '提货地址',
        keyName: 'pickupResolves',
        discripton: '统仓共配时除发货仓外的其它仓库地址；如有多个，请用“；”隔开'
    },
    {
        id: 39,
        name: '地址信息',
        reWriteliName: '站点编号',
        reWriteliName1: '站点编号',
        keyName: 'stationNo',
        discripton: ''
    },
    {
        id: 38,
        name: '地址信息',
        reWriteliName: '收货站点',
        reWriteliName1: '收货站点',
        keyName: 'address',
        discripton: '收货地址的简称；如宝山区华兹奔腾大厦'
    },
    {
        id: 37,
        name: '地址信息',
        reWriteliName: '收货城市',
        reWriteliName1: '收货城市',
        keyName: 'city',
        discripton: ''
    },
    {
        id: 36,
        name: '地址信息',
        reWriteliName: '收货区县',
        reWriteliName1: '收货区县',
        keyName: 'district',
        discripton: ''
    },
    {
        id: 35,
        name: '地址信息',
        reWriteliName: '收货地址经度',
        reWriteliName1: '收货地址经度',
        keyName: 'longitude',
        discripton: ''
    },
    {
        id: 34,
        name: '地址信息',
        reWriteliName: '收货地址纬度',
        reWriteliName1: '收货地址纬度',
        keyName: 'latitude',
        discripton: ''
    },
    {
        id: 33,
        name: '运单信息',
        reWriteliName: '分组序号',
        reWriteliName1: '分组序号',
        keyName: 'serialNumber',
        discripton: '用来作为合并运单的标识，分组序号相同即可合并为同一运单'
    },
    {
        id: 32,
        name: '运单信息',
        reWriteliName: '外部订单号',
        reWriteliName1: '外部订单号',
        keyName: 'externalId',
        discripton: '用户自建系统中的订单号，与系统中的运单号对应'
    },
    {
        id: 31,
        name: '运单信息',
        reWriteliName: '发货人姓名',
        reWriteliName1: '发货人姓名',
        keyName: 'shipperName',
        discripton: ''
    },
    {
        id: 30,
        name: '运单信息',
        reWriteliName: '发货人电话',
        reWriteliName1: '发货人电话',
        keyName: 'shipperTelephoneNo',
        discripton: ''
    },
    {
        id: 29,
        name: '运单信息',
        reWriteliName: '收货人姓名',
        reWriteliName1: '收货人姓名',
        keyName: 'customerName',
        discripton: ''
    },
    {
        id: 28,
        name: '运单信息',
        reWriteliName: '收货人电话',
        reWriteliName1: '收货人电话',
        keyName: 'customerTelephoneNo',
        discripton: ''
    },
    {
        id: 27,
        name: '运单信息',
        reWriteliName: '不收货时间',
        reWriteliName1: '不收货时间',
        keyName: 'excludeTimeTemps',
        discripton:
            '在收货时间段内的不收货时间点，格式12：00-14：00；如有多个，请用分号“；”隔开'
    },
    {
        id: 26,
        name: '运单信息',
        reWriteliName: '交接时间',
        reWriteliName1: '交接时间',
        keyName: 'handOverTime',
        discripton: '门店的交接货时长，单位为分钟'
    },
    {
        id: 25,
        name: '运单信息',
        reWriteliName: '配送方式',
        reWriteliName1: '配送方式',
        keyName: 'deliveryMethod',
        discripton: '包括拼单、不拼单2种配送方式'
    },
    {
        id: 24,
        name: '运单信息',
        reWriteliName: '回单要求',
        reWriteliName1: '回单要求',
        keyName: 'receiptMethod',
        discripton: '包括无需回单、原单返回、打收条、签信封、签回单盖章、传真返回、签回单'
    },
    {
        id: 23,
        name: '运单信息',
        reWriteliName: '回单数量',
        reWriteliName1: '回单数量',
        keyName: 'receiptQuantity',
        discripton: ''
    },
    {
        id: 22,
        name: '商品信息',
        reWriteliName: '商品名称',
        reWriteliName1: '商品名称',
        keyName: 'goodsName',
        discripton: ''
    },
    {
        id: 21,
        name: '商品信息',
        reWriteliName: '储藏方式',
        reWriteliName1: '储藏方式',
        keyName: 'storageMethod',
        discripton: '包括常温、冷藏、冷冻'
    },
    {
        id: 20,
        name: '商品信息',
        reWriteliName: '商品规格',
        reWriteliName1: '商品规格',
        keyName: 'goodsSpecification',
        discripton: ''
    },
    {
        id: 19,
        name: '商品信息',
        reWriteliName: '商品单位',
        reWriteliName1: '商品单位',
        keyName: 'goodsUnit',
        discripton: ''
    },
    {
        id: 18,
        name: '商品信息',
        reWriteliName: '是否特殊商品',
        reWriteliName1: '是否特殊商品',
        keyName: 'isSpecialGoods',
        discripton: '用来表示该运单能否被拆单'
    },
    {
        id: 17,
        name: '商品信息',
        reWriteliName: '商品长(m)',
        reWriteliName1: '商品长(m)',
        keyName: 'goodsTotalLength',
        discripton: ''
    },
    {
        id: 16,
        name: '商品信息',
        reWriteliName: '商品宽(m)',
        reWriteliName1: '商品宽(m)',
        keyName: 'goodsTotalWidth',
        discripton: ''
    },
    {
        id: 15,
        name: '商品信息',
        reWriteliName: '商品高(m)',
        reWriteliName1: '商品高(m)',
        keyName: 'goodsTotalHeight',
        discripton: ''
    },
    {
        id: 14,
        name: '商品信息',
        reWriteliName: '商品总金额',
        reWriteliName1: '商品总金额',
        keyName: 'totalPrice',
        discripton: ''
    },
    {
        id: 13,
        name: '商品信息',
        reWriteliName: '商品备注',
        reWriteliName1: '商品备注',
        keyName: 'goodsNote',
        discripton: ''
    },
    {
        id: 12,
        name: '费用信息',
        reWriteliName: '运费计价单位',
        reWriteliName1: '运费计价单位',
        keyName: 'unit',
        discripton: ''
    },
    {
        id: 11,
        name: '费用信息',
        reWriteliName: '运费单价',
        reWriteliName1: '运费单价',
        keyName: 'freightFeesUnitPrice',
        discripton: ''
    },
    {
        id: 10,
        name: '费用信息',
        reWriteliName: '运费',
        reWriteliName1: '运费',
        keyName: 'freightFees',
        discripton: ''
    },
    {
        id: 9,
        name: '费用信息',
        reWriteliName: '保价费',
        reWriteliName1: '保价费',
        keyName: 'valuationFees',
        discripton: ''
    },
    {
        id: 8,
        name: '费用信息',
        reWriteliName: '包装费',
        reWriteliName1: '包装费',
        keyName: 'packingFees',
        discripton: ''
    },
    {
        id: 7,
        name: '费用信息',
        reWriteliName: '配送费',
        reWriteliName1: '配送费',
        keyName: 'shippingFees',
        discripton: ''
    },
    {
        id: 6,
        name: '费用信息',
        reWriteliName: '拣货费',
        reWriteliName1: '拣货费',
        keyName: 'pickingFees',
        discripton: ''
    },
    {
        id: 5,
        name: '费用信息',
        reWriteliName: '其它费用',
        reWriteliName1: '其它费用',
        keyName: 'otherFees',
        discripton: ''
    },
    {
        id: 4,
        name: '费用信息',
        reWriteliName: '付款方式',
        reWriteliName1: '付款方式',
        keyName: 'payMethod',
        discripton:
            '包含现付、到付、回单付、月结、免费5种付款方式'
    },
    {
        id: 3,
        name: '费用信息',
        reWriteliName: '上楼费',
        reWriteliName1: '上楼费',
        keyName: 'upstairsFees',
        discripton: ''
    },
    {
        id: 2,
        name: '其他信息',
        reWriteliName: '最大可进车型',
        reWriteliName1: '最大可进车型',
        keyName: 'maxVehicleType',
        discripton: '当前收货站点的最大可进车型，需要先在车型管理中对车型进行排序'
    },
    {
        id: 1,
        name: '其他信息',
        reWriteliName: '备注',
        reWriteliName1: '备注',
        keyName: 'note',
        discripton: '运单备注信息'
    }
    ]
    if (myTemplateID === '') {
        // console.log(arr)
        if (arr.length > 0) {
            var newEditt = []
            arr1.forEach(function (item, i) {
                var res = userNewToInStamOfOldOne(item)
                newEditt.push(res)
            })
            arr1 = newEditt;
        }
    } else {
        var newEditt = []
        arr1.forEach(function (item, i) {
            var res = userNewToInStamOfOldOne(item)
            newEditt.push(res)
        })
        arr1 = newEditt;
    }
    var newModelBody1 = [];
    arr1.forEach(function (item) {
        var str = JSON.stringify(item)
        newModelBody1.push({
            td1: item.name ? item.name : '',
            td2: item.reWriteliName1 ? item.reWriteliName1 : '',
            td3: item.discripton ? item.discripton : '',
            td4: "<input type='checkbox' name='' lay-skin='primary'  value='" + str + "'id='yin" + item.id + "'" + "'data-id='yin" + item.id + "'" + "'lay-filter='allcheckd' >",
            td5: item.reWriteliName ? item.reWriteliName : '',
            // td5: "<div style='width:90%;height:90%;margin:0 auto ;border:1px solid rgba(232,230,230,1);background:rgba(255,255,255,1);'>" + item.reWriteliName + "<div>",

        });
    })
    tableList1('tableCont1', newModelHead1, null, newModelBody1, '450', callBackFunction);
    setTimeout(function () {
        // table.reload('tableCont1')
        // table.resize('tableCont1'); //重置表格尺寸
        var resizeEvent = window.document.createEvent('UIEvents');
        resizeEvent.initUIEvent('resize', true, false, window, 0);
        window.dispatchEvent(resizeEvent);
    }, 0)
}

// arr 里本来就有的替换固定的
function userNewToInStamOfOldOne(iten) {
    // console.log(iten)
    var res
    arr.forEach(function (item) {
        // console.log(item)
        if (iten.id === item.id) {
            iten.reWriteliName = item.reWriteliName
            res = iten;
        } else {
            res = iten
        }
    })
    return res
}

//监听单元格编辑
function callBackFunction(res) {
    // console.log('999', res)
}
//封装成方法，通过某个属性去重
function filterRepeat(arr, prop) {
    return arr.filter(function (element, index, self) {
        return self.findIndex(function (el) { el[prop] == element[prop] }) === index
    })
}
//自定义去重方法
function filterRepeat2(arr, compareFn) {
    return arr.filter(function (element, index, self) {
        return self.findIndex(function (el) {
            compareFn(el, element)
        }) === index
    })
}
//加载到数组原型上
Array.prototype.filterRepeat = function () {
    if (typeof arguments[0] == 'string') return filterRepeat(this, arguments[0])
    return filterRepeat2(this, arguments[0])
}
// 确定添加列名按钮
$('.addclon_btn').on('click', function () {
    var arrArry = []
    var chekedList = $('.new_dialog_content1 .layui-form-checked');
    chekedList.each(function () {
        var newe = $(this).prev()[0].value;
        var obj = JSON.parse(newe)
        arrArry.push(obj);
    });

    // setTimeout(function () {
    // console.log(arrArry)
    // }, 10)
    var valeee = $('.new_dialog_content .dialog_body_son .layui-form-radioed').prev().val();

    if (valeee === 'intelligence') {
        moren = 1;
    } else {
        moren = 2;
    }
    if (moren !== 2) {
        var newArry1 = arrArry;
        arrArry.forEach(function (item) {
            var ress = getDontHaveItem(item)
            // console.log('新对象', ress)
            newArry1.forEach(function (item) {
                if (item.id === ress.id) {
                    item.reWriteliName = ress.reWriteliName;
                }
            })
        })
        // arr = []
        var arrw = arr;
        arrArry = newArry1
        // console.log(arrArry)
        // console.log(arrw)
        renderNewModelTable(arrArry, moren, arrw)
        arrw = []
    } else {
        var newArry1 = arrArry;
        arrArry.forEach(function (item) {
            var ress = getDontHaveItem(item)
            // console.log('新对象', ress)
            newArry1.forEach(function (item) {
                if (item.id === ress.id) {
                    item.reWriteliName = ress.reWriteliName;
                }
            })
        })
        arrArry = newArry1
        var arrw = arr;
        renderNewModelTable(arrArry, moren, arrw)
        arrw = []
    }

    $('.new_dialog1').hide()
    $('.new_dialog').show()
    removeCheckedInput()

})
// 寻找没有的item
function getDontHaveItem(iten) {
    var obj = {};
    arr.forEach(function (item) {
        if (iten.id === item.id && iten.reWriteliName === item.reWriteliName) {
            obj = item
        } else {
            return
        }
    })
    return obj
}

function tableList1(tableId, tableHead, tableFoot, tableBody, fullHeight, callBack, otherData) {
    // 渲染前获取滚动距离
    if ($('.rightCont .layui-table-main .layui-table').length == 1) {
        XQ_table_oldScrollLeft = $('.rightCont .layui-table-main .layui-table').position().left;
    }
    // debugger
    layui.use(['table', 'tableMerge'], function () {
        var table = layui.table, tableMerge = layui.tableMerge;
        table.render({
            elem: '#' + tableId,
            // width: 'full',
            height: fullHeight,
            limit: 9999999999999,
            page: false,
            footer: true,
            cellMinWidth: 60,
            cols: tableHead,
            foot: tableFoot,
            data: tableBody,
            text: {
                none: otherData && otherData.text ? otherData.text : '无数据'
            },
            done: function (res) { // 渲染完成后回调事件
                tableMerge.render(this)
                // table.reload('tableCont1')
                $('.new_dialog_content1 .layui-table-body tbody tr').find('td[data-field=td5]').addClass('reed2')
                $('.new_dialog_content1 .layui-table-body tbody tr').find('td[data-field=td5]').children("div").addClass('reed')
                $('.new_dialog_content1 .layui-border-box thead tr').find('th[data-field=td5]').addClass('reed2')
                if (callBack) {
                    callBack(res)
                }
                $('.rightCont .layui-table-main').scrollLeft(-(XQ_table_oldScrollLeft)); // 横向滚动赋值
            }
        });
    });
}
function tableList2(tableId, tableHead, tableFoot, tableBody, fullHeight, callBack, otherData) {
    // 渲染前获取滚动距离
    if ($('.rightCont .layui-table-main .layui-table').length == 1) {
        XQ_table_oldScrollLeft = $('.rightCont .layui-table-main .layui-table').position().left;
    }
    // debugger
    layui.use(['table', 'tableMerge'], function () {
        var table = layui.table, tableMerge = layui.tableMerge;
        table.render({
            elem: '#' + tableId,
            // width: 'full',
            height: fullHeight,
            limit: 9999999999999,
            page: false,
            footer: true,
            cellMinWidth: 60,
            cols: tableHead,
            foot: tableFoot,
            data: tableBody,
            text: {
                none: otherData && otherData.text ? otherData.text : '无数据'
            },
            done: function (res) { // 渲染完成后回调事件
                // $('.layui-table-body tbody tr').find(['data-field=td2']).next().css('background', 'red');
                // console.log($('.new_dialog_content .layui-table-body tbody tr').find('td[data-field=td2]'))
                $('.new_dialog_content .layui-table-body tbody tr').find('td[data-field=td2]').addClass('reed2')
                $('.new_dialog_content .layui-table-body tbody tr').find('td[data-field=td2]').children("div").addClass('reed')
                $('.new_dialog_content .layui-border-box thead tr').find('th[data-field=td2]').addClass('reed2')
                // $('.new_dialog_content .layui-table-body tbody tr').find('td[data-field=td2]').children("input").addClass('reed')
                if (callBack) {
                    callBack(res)
                }
                $('.rightCont .layui-table-main').scrollLeft(-(XQ_table_oldScrollLeft)); // 横向滚动赋值
                // $('.rightCont .layui-table-main .layui-table-total .layui-table').scrollLeft(- (XQ_table_oldScrollLeft)); // 横向滚动赋值
            }
        });
        // form.render('checkbox');
    });
}
$('.close_add_model').on('click', function () {
    $('.new_dialog1').hide()
    $('.new_dialog').show()
    removeCheckedInput()
    setTimeout(function () {
        table.reload('tableCont')
        var myEvent = new Event('resize');
        window.dispatchEvent(myEvent);
        table.resize('tableCont'); //重置表格尺寸
    }, 0)

})
function removeCheckedInput() {
    var chekedList = $('.new_dialog_content1 .layui-form-checked')
    var arrArry = [];
    chekedList.each(function () {
        arrArry.push($(this));
    });
    arrArry.forEach(function (item) {
        item.removeClass('layui-form-checked')
    })
}
// 改造编辑数据
function reSetObjToArray(obj, e) {
    var arr = []
    // console.log(obj)
    moren = obj.templateType;
    for (var i in obj) {
        var k = {}
        k[i] = obj[i]
        k.key = k[i]
        if (obj[i] && i !== 'id' && i !== 'templateName' && i !== 'templateType') {
            var res = reTurenItem(i, e, obj[i])
            arr.push(res)
        }
    }
    return arr
}

function reTurenItem(key, i, v) {
    var iten
    var arrNew1 = [
        {
            id: 1013,
            ismust: 'is',
            name: '发货地址',
            reWriteliName: '发货地址',
            reWriteliName1: '发货地址',
            keyName: 'originAddress',
            discripton: ''
        },
        {
            id: 1012,
            ismust: 'is',
            name: '收货地址',
            reWriteliName: '收货地址',
            reWriteliName1: '收货地址',
            keyName: 'detailAddress',
            discripton: ''
        },
        {
            id: 1011,
            ismust: 'is',
            name: '下单时间',
            reWriteliName: '下单时间',
            reWriteliName1: '下单时间',
            keyName: 'orderTime',
            discripton: '指客户的下单时间或生成运单的时间;格式为：2018-01-01 08:00'
        },
        {
            id: 1010,
            ismust: 'is',
            name: '期望送达时间起',
            reWriteliName: '期望送达时间起',
            reWriteliName1: '期望送达时间起',
            keyName: 'expectedDeliveryStartTime',
            discripton: '货物期望送达的最早时间窗口;格式为：2018-01-01 08:00'
        },
        {
            id: 1009,
            ismust: 'is',
            name: '期望送达时间止',
            reWriteliName: '期望送达时间止',
            reWriteliName1: '期望送达时间止',
            keyName: 'expectedDeliveryEndTime',
            discripton: '货物期望送达的最晚时间窗口;格式为：2018-01-01 08:00'
        },
        {
            id: 1008,
            ismust: 'is',
            name: '商品数量',
            reWriteliName: '商品数量',
            reWriteliName1: '商品数量',
            keyName: 'quantity',
            discripton: ''
        },
        {
            id: 1007,
            ismust: 'is',
            name: '商品总体积',
            reWriteliName: '商品总体积(m3)',
            reWriteliName1: '商品总体积(m3)',
            keyName: 'volume',
            discripton: ''
        },
        {
            id: 1006,
            ismust: 'is',
            name: '商品总重量',
            reWriteliName: '商品总重量(kg)',
            reWriteliName1: '商品总重量(kg)',
            keyName: 'load',
            discripton: ''
        }
    ]
    var arrNew2 = [
        {
            id: 1005,
            ismust: 'is',
            name: '发货地址',
            reWriteliName: '发货地址',
            reWriteliName1: '发货地址',
            keyName: 'originAddress',
            discripton: ''
        },
        {
            id: 1004,
            ismust: 'is',
            name: '收货地址',
            reWriteliName: '收货地址',
            reWriteliName1: '收货地址',
            keyName: 'detailAddress',
            discripton: ''
        },
        {
            id: 1003,
            istuijian: 'is',
            name: '商品数量',
            reWriteliName: '商品数量',
            reWriteliName1: '商品数量',
            keyName: 'quantity',
            discripton: ''
        },
        {
            id: 1002,
            istuijian: 'is',
            name: '商品总体积',
            reWriteliName: '商品总体积(m3)',
            reWriteliName1: '商品总体积(m3)',
            keyName: 'volume',
            discripton: ''
        },
        {
            id: 1001,
            istuijian: 'is',
            name: '商品总重量',
            reWriteliName: '商品总重量(kg)',
            reWriteliName1: '商品总重量(kg)',
            keyName: 'load',
            discripton: ''
        }
    ]
    var lastArray = [
        {
            id: 41,
            name: '地址信息',
            reWriteliName: '片区号',
            reWriteliName1: '片区号',
            keyName: 'areaName',
            discripton: '配送订单时的线路号，在规划线路按片区运营时可根据片区号进行规划'
        },
        {
            id: 40,
            name: '地址信息',
            reWriteliName: '提货地址',
            reWriteliName1: '提货地址',
            keyName: 'pickupResolves',
            discripton: '统仓共配时除发货仓外的其它仓库地址；如有多个，请用“；”隔开'
        },
        {
            id: 39,
            name: '地址信息',
            reWriteliName: '站点编号',
            reWriteliName1: '站点编号',
            keyName: 'stationNo',
            discripton: ''
        },
        {
            id: 38,
            name: '地址信息',
            reWriteliName: '收货站点',
            reWriteliName1: '收货站点',
            keyName: 'address',
            discripton: '收货地址的简称；如宝山区华兹奔腾大厦'
        },
        {
            id: 37,
            name: '地址信息',
            reWriteliName: '收货城市',
            reWriteliName1: '收货城市',
            keyName: 'city',
            discripton: ''
        },
        {
            id: 36,
            name: '地址信息',
            reWriteliName: '收货区县',
            reWriteliName1: '收货区县',
            keyName: 'district',
            discripton: ''
        },
        {
            id: 35,
            name: '地址信息',
            reWriteliName: '收货地址经度',
            reWriteliName1: '收货地址经度',
            keyName: 'longitude',
            discripton: ''
        },
        {
            id: 34,
            name: '地址信息',
            reWriteliName: '收货地址纬度',
            reWriteliName1: '收货地址纬度',
            keyName: 'latitude',
            discripton: ''
        },
        {
            id: 33,
            name: '运单信息',
            reWriteliName: '分组序号',
            reWriteliName1: '分组序号',
            keyName: 'serialNumber',
            discripton: '用来作为合并运单的标识，分组序号相同即可合并为同一运单'
        },
        {
            id: 32,
            name: '运单信息',
            reWriteliName: '外部订单号',
            reWriteliName1: '外部订单号',
            keyName: 'externalId',
            discripton: '用户自建系统中的订单号，与系统中的运单号对应'
        },
        {
            id: 31,
            name: '运单信息',
            reWriteliName: '发货人姓名',
            reWriteliName1: '发货人姓名',
            keyName: 'shipperName',
            discripton: ''
        },
        {
            id: 30,
            name: '运单信息',
            reWriteliName: '发货人电话',
            reWriteliName1: '发货人电话',
            keyName: 'shipperTelephoneNo',
            discripton: ''
        },
        {
            id: 29,
            name: '运单信息',
            reWriteliName: '收货人姓名',
            reWriteliName1: '收货人姓名',
            keyName: 'customerName',
            discripton: ''
        },
        {
            id: 28,
            name: '运单信息',
            reWriteliName: '收货人电话',
            reWriteliName1: '收货人电话',
            keyName: 'customerTelephoneNo',
            discripton: ''
        },
        {
            id: 27,
            name: '运单信息',
            reWriteliName: '不收货时间',
            reWriteliName1: '不收货时间',
            keyName: 'excludeTimeTemps',
            discripton:
                '在收货时间段内的不收货时间点，格式12：00-14：00；如有多个，请用分号“；”隔开'
        },
        {
            id: 26,
            name: '运单信息',
            reWriteliName: '交接时间',
            reWriteliName1: '交接时间',
            keyName: 'handOverTime',
            discripton: '门店的交接货时长，单位为分钟'
        },
        {
            id: 25,
            name: '运单信息',
            reWriteliName: '配送方式',
            reWriteliName1: '配送方式',
            keyName: 'deliveryMethod',
            discripton: '包括拼单、不拼单2种配送方式'
        },
        {
            id: 24,
            name: '运单信息',
            reWriteliName: '回单要求',
            reWriteliName1: '回单要求',
            keyName: 'receiptMethod',
            discripton: '包括无需回单、原单返回、打收条、签信封、签回单盖章、传真返回、签回单'
        },
        {
            id: 23,
            name: '运单信息',
            reWriteliName: '回单数量',
            reWriteliName1: '回单数量',
            keyName: 'receiptQuantity',
            discripton: ''
        },
        {
            id: 22,
            name: '商品信息',
            reWriteliName: '商品名称',
            reWriteliName1: '商品名称',
            keyName: 'goodsName',
            discripton: ''
        },
        {
            id: 21,
            name: '商品信息',
            reWriteliName: '储藏方式',
            reWriteliName1: '储藏方式',
            keyName: 'storageMethod',
            discripton: '包括常温、冷藏、冷冻'
        },
        {
            id: 20,
            name: '商品信息',
            reWriteliName: '商品规格',
            reWriteliName1: '商品规格',
            keyName: 'goodsSpecification',
            discripton: ''
        },
        {
            id: 19,
            name: '商品信息',
            reWriteliName: '商品单位',
            reWriteliName1: '商品单位',
            keyName: 'goodsUnit',
            discripton: ''
        },
        {
            id: 18,
            name: '商品信息',
            reWriteliName: '是否特殊商品',
            reWriteliName1: '是否特殊商品',
            keyName: 'isSpecialGoods',
            discripton: '用来表示该运单能否被拆单'
        },
        {
            id: 17,
            name: '商品信息',
            reWriteliName: '商品长(m)',
            reWriteliName1: '商品长(m)',
            keyName: 'goodsTotalLength',
            discripton: ''
        },
        {
            id: 16,
            name: '商品信息',
            reWriteliName: '商品宽(m)',
            reWriteliName1: '商品宽(m)',
            keyName: 'goodsTotalWidth',
            discripton: ''
        },
        {
            id: 15,
            name: '商品信息',
            reWriteliName: '商品高(m)',
            reWriteliName1: '商品高(m)',
            keyName: 'goodsTotalHeight',
            discripton: ''
        },
        {
            id: 14,
            name: '商品信息',
            reWriteliName: '商品总金额',
            reWriteliName1: '商品总金额',
            keyName: 'totalPrice',
            discripton: ''
        },
        {
            id: 13,
            name: '商品信息',
            reWriteliName: '商品备注',
            reWriteliName1: '商品备注',
            keyName: 'goodsNote',
            discripton: ''
        },
        {
            id: 12,
            name: '费用信息',
            reWriteliName: '运费计价单位',
            reWriteliName1: '运费计价单位',
            keyName: 'unit',
            discripton: ''
        },
        {
            id: 11,
            name: '费用信息',
            reWriteliName: '运费单价',
            reWriteliName1: '运费单价',
            keyName: 'freightFeesUnitPrice',
            discripton: ''
        },
        {
            id: 10,
            name: '费用信息',
            reWriteliName: '运费',
            reWriteliName1: '运费',
            keyName: 'freightFees',
            discripton: ''
        },
        {
            id: 9,
            name: '费用信息',
            reWriteliName: '保价费',
            reWriteliName1: '保价费',
            keyName: 'valuationFees',
            discripton: ''
        },
        {
            id: 8,
            name: '费用信息',
            reWriteliName: '包装费',
            reWriteliName1: '包装费',
            keyName: 'packingFees',
            discripton: ''
        },
        {
            id: 7,
            name: '费用信息',
            reWriteliName: '配送费',
            reWriteliName1: '配送费',
            keyName: 'shippingFees',
            discripton: ''
        },
        {
            id: 6,
            name: '费用信息',
            reWriteliName: '拣货费',
            reWriteliName1: '拣货费',
            keyName: 'pickingFees',
            discripton: ''
        },
        {
            id: 5,
            name: '费用信息',
            reWriteliName: '其它费用',
            reWriteliName1: '其它费用',
            keyName: 'otherFees',
            discripton: ''
        },
        {
            id: 4,
            name: '费用信息',
            reWriteliName: '付款方式',
            reWriteliName1: '付款方式',
            keyName: 'payMethod',
            discripton:
                '包含现付、到付、回单付、月结、免费5种付款方式'
        },
        {
            id: 3,
            name: '费用信息',
            reWriteliName: '上楼费',
            reWriteliName1: '上楼费',
            keyName: 'upstairsFees',
            discripton: ''
        },
        {
            id: 2,
            name: '其他信息',
            reWriteliName: '最大可进车型',
            reWriteliName1: '最大可进车型',
            keyName: 'maxVehicleType',
            discripton: '当前收货站点的最大可进车型，需要先在车型管理中对车型进行排序'
        },
        {
            id: 1,
            name: '其他信息',
            reWriteliName: '备注',
            reWriteliName1: '备注',
            keyName: 'note',
            discripton: '运单备注信息'
        }
    ]
    var forlist = []
    if (i === 0) {
        forlist = arrNew1.concat(lastArray)
        // console.log('零')
    } else {
        forlist = arrNew2.concat(lastArray)
        // console.log('一')
    }
    forlist.forEach(function (item) {
        if (item.keyName === key) {
            item.reWriteliName = v
            iten = item
        }
    })
    return iten
}
function getTransportInfoList() {
    AJAX(TRANSPORT_AJAX_URL + '/xq-route-plan-tms/mappingTemplate/findTempList', '', getResRetrunTempName)
}
function getResRetrunTempName(res) {
    // console.log(res)
    var data = [];
    if (res.code === 100) {
        allModelList = res.result
        if (res.result.length >= 0) {
            if (res.result.length >= 3) {
                $('.addBTTn').css('color', '#0D92EF')
                // $('.addBTTn').prop('disabled', 'disabled');
                // $('.addBTTn').addClass('layui-radio-disbaled layui-disabled');

            } else {
                $('.addBTTn').css('color', '#0D92EF')
                // $('.addBTTn').attr('disabled', false);
                // $('.addBTTn').removeClass('layui-radio-disbaled layui-disabled');

            }
            res.result.forEach(function (item) {
                data.push({
                    id: item.id,
                    name: item.templateName
                })
            })
        }
    }
    var getTpl = demo.innerHTML
        , view = document.getElementById('tempIdOne');
    laytpl(getTpl).render(data, function (html) {
        view.innerHTML = html;
    });
}// yinc
